我一直在尝试测试我使用 nuxt 的文件(asyncData 和 fetch hooks),我在测试 vue.js 正常生命周期时没有问题,但我注意到 vue/test-utils 没有给出明确的说明测试 nuxt 的钩子(Hook)。
登录.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
})
})
最佳答案
Gyen Abubakar's answer如果您只想使用模拟数据测试组件的行为,这可能是一个解决方案。但请记住,asyncData 和 fetch Hook 未经过测试,您可能需要测试它们以获得更好的单元测试。
如果你想测试你的 asyncData 和 fetch 钩子(Hook),你需要在安装组件后添加:
异步数据
wrapper = shallowMount(Login); wrapper.setData({ ...(await wrapper.vm.$options.asyncData({ store })) // add more context here });
获取钩子(Hook)
wrapper = shallowMount(Login); await Login.fetch.call(wrapper.vm); // using `call` to inject `this`
关于vue.js - 如何测试 nuxt.js asyncData 和获取钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63638214/