Vue test-utils 如何测试 router.push() [英] Vue test-utils how to test a router.push()
问题描述
在我的组件中,我有一个方法可以执行 router.push()
In my component , I have a method which will execute a 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 - 我收到一个错误
1 - I get an error
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 路由已被调用
2 - How I should write the expect() to be sure that this /home route has been called
感谢反馈
推荐答案
您正在做的事情碰巧有效,但我认为是错误的,并且还导致您在测试路由器时出现问题.您正在组件中导入路由器:
You are doing something that happens to work, but I believe is wrong, and also is causing you problems to test the router. You're importing the router in your component:
import router from "@/router";
然后立即调用它的push
:
router.push("/home");
我不知道您究竟是如何安装路由器的,但通常您会执行以下操作:
I don't know how exactly you're installing the router, but usually you do something like:
new Vue({
router,
store,
i18n,
}).$mount('#app');
安装Vue插件.我敢打赌你已经这样做了(实际上,这种机制是将 $route
暴露给你的组件).在示例中,还安装了一个 vuex 存储和对 vue-i18n 的引用.
To install Vue plugins. I bet you're already doing this (in fact, is this mechanism that expose $route
to your component). In the example, a vuex store and a reference to vue-i18n are also being installed.
这将在所有组件中公开一个 $router
成员.您可以从 this
调用它作为 $router
:
This will expose a $router
member in all your components. Instead of importing the router and calling its push
directly, you could call it from this
as $router
:
this.$router.push("/home");
现在,这使测试更容易,因为您可以在测试时通过 mocks
属性将伪路由器传递给您的组件,就像使用 $route一样代码>已经:
Now, thise makes testing easier, because you can pass a fake router to your component, when testing, via the mocks
property, just as you're doing with $route
already:
const push = jest.fn();
const $router = {
push: jest.fn(),
}
...
mocks: {
$route,
$router,
}
然后,在您的测试中,您断言 push
已被调用:
And then, in your test, you assert against push
having been called:
expect(push).toHaveBeenCalledWith('/the-desired-path');
这篇关于Vue test-utils 如何测试 router.push()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!