Reputation: 328
Here is the code from my component an the current test I have:
// component script
import { mapActions } from 'vuex'
export default {
name: 'foo',
mounted () {
this.firstMethod()
.then(() => {
this.secondMethod()
})
.then(() => {
this.thirdMethod()
})
},
methods: {
...mapActions([
'firstMethod',
'secondMethod',
'thirdMethod'
])
}
}
// test
import { shallow, createLocalVue } from 'vue-test-utils'
import Vuex from 'vuex'
import Foo from '../Foo.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Foo.vue', () => {
let actions
let store
let wrapper
beforeEach(() => {
actions = {
firstMethod: sinon.stub().resolves(),
secondMethod: sinon.stub().resolves(),
thirdMethod: sinon.stub(),
}
store = new Vuex.Store({
actions
})
wrapper = shallow(Foo, { store, localVue })
})
it.only('calls store actions when mounted', () => {
expect(actions.firstMethod.called).toBe(true) // succeedes
expect(actions.secondMethod.called).toBe(true) // fails
expect(actions.thirdMethod.called).toBe(true) // fails
})
})
I was expecting all three expects
to succeed, since I understand that the .resolves()
method makes the stub
to return a resolved promise, and that would in turn trigger the next call under the then
method on the component. But its not.
How should I test that the Vuex actions are indeed called?
I'm open to the idea of multiple tests instead of just one, if that makes sense. Or even to refactor the 3 calls to something else, as long as they are called in that order when successful.
Thanks!
Upvotes: 0
Views: 1061
Reputation: 328
Ok, so I changed the structure of my component mount method, but the test also works with the original code.
Here is the updated component with the test.
// component script
import { mapActions } from 'vuex'
export default {
name: 'foo',
mounted () {
this.mount()
},
methods: {
async mount () {
await this.firstMethod()
await this.secondMethod()
await this.thirdMethod()
},
...mapActions([
'firstMethod',
'secondMethod',
'thirdMethod'
])
}
}
// test
import { shallow, createLocalVue } from 'vue-test-utils'
import Vuex from 'vuex'
import Foo from '../Foo.vue'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Foo.vue', () => {
let actions
let store
let wrapper
beforeEach(() => {
actions = {
firstMethod: sinon.stub().resolves(),
secondMethod: sinon.stub().resolves(),
thirdMethod: sinon.stub().resolves()
}
store = new Vuex.Store({
actions
})
wrapper = shallow(Foo, { store, localVue })
})
it('calls store actions when mounted', async () => {
await expect(actions.firstMethod.called).toBe(true)
await expect(actions.secondMethod.called).toBe(true)
await expect(actions.thirdMethod.called).toBe(true)
})
})
I hope this helps someone!
Upvotes: 1