Reputation: 454
currently I am writing tests for Vue.js app and got stuck with the problem: if there are some tests for routing, paths in href
are modified in each next test according to previous ones.
For example, if in first test I simulate click on a link with href='document/123'
and check the vm.$router.history.path
, it will correctly show document/123
, but if in the next test I'll try to do the same, vm.$router.history.path
will show document/document/123
and keep adding 'document' in path with every next test.
It is strange and looks like router
keeps existing during all tests in describe
block even though I have beforeEach
hook where I re-initialize Vue and usage of all plugins alongside with Vue-router and in afterEach
hook I call $destroy()
method on Vue instance.
Is there any way to modify or reset vm.$router.history
object or its properties in afterEach
hook or am I missing something else?
Here is code of the test:
import Vue from 'vue'
import Search from '../../../src/Search.vue';
import router from '../../../src/router';
describe('Search', () => {
let vm;
beforeEach((done) => {
const container = document.createElement('div');
vm = new Vue({
router,
render: h => h(Search),
}).$mount(container);
done();
});
afterEach((done) => {
vm.$destroy();
done();
});
it('should navigate to single page when user clicks on "More" button', (done) => {
let moreButton = vm.$el.querySelector('.btn');
let clickEvent = new window.Event('click');
moreButton.dispatchEvent(clickEvent);
Vue.nextTick().then(() => {
expect(vm.$router.history.current.path).to.equal('/document/1548'); // passes
done();
});
});
it('should navigate to single page when user clicks on document title', (done) => {
let link = vm.$el.querySelector('h6 a');
let clickEvent = new window.Event('click');
link.dispatchEvent(clickEvent);
Vue.nextTick().then(() => {
expect(vm.$router.history.current.path).to.equal('/document/1548'); // fails, actual path is /document/document/1548
done();
});
});
});
Upvotes: 6
Views: 1487
Reputation: 111
Old question but incase others are encountering the same issue, the solution is described here: https://github.com/vuejs/vue-test-utils/issues/1681
Specifically change the 'mode' parameter in your test suite to 'abstract'. Otherwise the route will be based on window.location which is preserved between tests. 'abstract' configures navigation to be based on the 'stack' which is instantiated with new instances of vue-router.
Locally I had to parameterize my instantiation of vue-router so that in production mode 'history' was used and when running the test suite 'abstract' was used.
Upvotes: 1