我一直在尝试测试使用 nuxt 的文件(asyncData 和 fetch hooks),测试 vue.js 正常生命周期没有问题,但我注意到 vue/test-utils 没有给出有关如何测试 nuxt 的明确说明钩子。
登录.vue
asyncData() {
const email = localStorage.getItem("email") || ""
const password = localStorage.getItem("password") || ""
return { email, password }
},
mounted() {
this.setMaxStep()
}
注册.vue
async fetch({ store, redirect, query }) {
const res = await store.dispatch("getSavedFormData")
if (res) {
store.dispatch("setNotification", {
message: "Previous application is loaded"
})
}
},
尝试像下面这样测试它,但我没有运气(也尝试了其他各种事情,但我不知道在哪里寻找信息)
import {
shallowMount,
config
} from "@vue/test-utils"
import Login from "../../../pages/login
describe("Login", () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(Login)
})
it("gets asyncData", async () => {
await wrapper.vm.asyncData
})
})
吉恩·阿布巴卡的回答 https://stackoverflow.com/a/65884007/4367224如果您只想使用模拟数据测试组件的行为,这可能是一个解决方案。但请记住,asyncData 和 fetch 挂钩尚未经过测试,您可能需要测试它们以获得更好的单元测试。
如果您想测试 asyncData 和 fetch 挂钩,则需要在安装组件后添加以下内容:
-
异步数据
wrapper = shallowMount(Login);
wrapper.setData({
...(await wrapper.vm.$options.asyncData({ store })) // add more context here
});
-
取钩
wrapper = shallowMount(Login);
await Login.fetch.call(wrapper.vm); // using `call` to inject `this`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)