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;
}
},
// ....
}
}
I want to test it...
I wrote the following specs..
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 - 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 - How I should write the expect() to be sure that this /home route has been called
thanks for feedback
Assuming that you have setup the pre-requisities correctly and similar to this
Just use
No problème I got it right... and I understand bettes thé this.$router usage
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:
Then calling its
push
right away:I don't know how exactly you're installing the router, but usually you do something like:
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.This will expose a
$router
member in all your components. Instead of importing the router and calling itspush
directly, you could call it fromthis
as$router
: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:And then, in your test, you assert against
push
having been called: