在我的组件中,我有一个方法将执行 router.push()
import router from "@/router";
// ...
export default {
// ...
methods: {
closeAlert: function() {
if (this.msgTypeContactForm == "success") {
router.push("/home");
} else {
return;
}
},
// ....
}
}
我想测试一下...
我写了以下规范..
it("should ... go to home page", async () => {
// given
const $route = {
name: "home"
},
options = {
...
mocks: {
$route
}
};
wrapper = mount(ContactForm, options);
const closeBtn = wrapper.find(".v-alert__dismissible");
closeBtn.trigger("click");
await wrapper.vm.$nextTick();
expect(alert.attributes().style).toBe("display: none;")
// router path '/home' to be called ?
});
1 - 我得到一个错误
console.error node_modules/@vue/test-utils/dist/vue-test-utils.js:15
[vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property asa read-only value
2 - 我应该如何编写 expect() 以确保此/home 路由已被调用
感谢反馈
最佳答案
您正在做的事情恰好有效,但我认为这是错误的,并且还会导致您在测试路由器时遇到问题。您正在组件中导入路由器:
import router from "@/router";
然后调用它的 push
马上:
router.push("/home");
我不知道你是如何安装路由器的,但通常你会这样做:
new Vue({
router,
store,
i18n,
}).$mount('#app');
安装 Vue 插件。我打赌你已经在这样做了(事实上,这种机制将 $route
暴露给你的组件)。在示例中,还安装了 vuex 商店和对 vue-i18n 的引用。
这将公开一个 $router
所有组件中的成员。而不是导入路由器并调用其 push
直接,你可以从this
调用它作为$router
:
this.$router.push("/home");
现在,这使测试更容易,因为您可以在测试时通过 mocks
将伪造的路由器传递给您的组件。属性(property),就像你对 $route
所做的一样已经:
const push = jest.fn();
const $router = {
push: jest.fn(),
}
...
mocks: {
$route,
$router,
}
然后,在您的测试中,您针对 push
断言被称为:
expect(push).toHaveBeenCalledWith('/the-desired-path');
关于vue.js - Vue test-utils 如何测试 router.push(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302536/