Testing `$watch` on `$route`
See original GitHub issueHi,
I have a test that is using a mock vuex store, and a real router. I want to test if an action is dispatched when the route changes.
I do something like:
SomeComponent:
export default {
created() {
this.$store.dispatch('someAction')
},
watch: {
'$route' (newVal, val) {
if (val.params.category !== newVal.params.category) {
this.$stoore.dispatch('someAction')
}
}
}
Test
import router from '../real-router'
describe('SomeComponent', () => {
let actions;
let store;
beforeEach(() => {
actions = {
someAction: jest.fn() // also tried sinon.mock()
}
store = new Vuex.Store({ state: {}, actions })
})
it('calls action on route change', () => {
mount(SomeComponent, { store, router })
router.push({ name: 'someNamedRoute', params: { category: { 'okok' }})
expect(actions.someAction.mocks.length).toBe(2)
})
})
})
For some reason, even though the $watch on the $route is triggering, the mock is not called again. I can confirm it does work in the created hook.
Is there something that would stop the action in a watch/route hook being called? Am I missing something? Or should I write this test different? I want to test that when the route changes, the action is called.
I am happy to contribute again if needed!
Thanks.
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (6 by maintainers)
Top Results From Across the Web
How to unit test VueJS watcher on $route - Stack Overflow
This is how I'm testing a watch on route change that adds the current route name as a css class to my app...
Read more >Chapter 10. Testing Vue Router
Testing router properties. Vue Router adds two instance properties when you install it on Vue: the $route property and the $router property ...
Read more >Vue.js 3 Unit Testing Routing Tutorial - KoderHQ
In this Vue tutorial we learn how to test the router and routing. We cover how to test with a local router and...
Read more >Testing Vue Router
This article will present two ways to test an application using Vue Router: ... We could use a real router, then navigate to...
Read more >Vue Router - Vue Testing Handbook
As usual, we start by importing the various modules for the test. Notably, we are importing the actual routes we will be using...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
For anyone else who comes across this issue it seems to be fixed without the need for vue-test-utils.
Working like the following:
Reopening (see above comment for repro).