In my vue component I am have a some methods firing off in the mounted lifecycle,
mounted() {
this.GET_WORKFLOW_TYPES()
.then(() => {
this.GET_WORKFLOW_EVENTS_BY_TYPE({workflow_type: this.audit.selectedWorkflowType})
});
},
The above are actions in my store and they are mapped into my component like the following,
methods: {
...mapActions([ACTION_TYPES.GET_WORKFLOW_TYPES, ACTION_TYPES.GET_WORKFLOW_EVENTS_BY_TYPE]);
}
I am wanting to test that both these functions get called in my unit test so I have tried,
it('Should render the audit component and it\'s children', async () => {
wrapper = mount(AdminAudit, { store, localVue});
//Does it retrieve the data we need
expect(actions.GET_WORKFLOW_TYPES).toHaveBeenCalled();
await wrapper.vm.$nextTick(() => {
expect(actions.GET_WORKFLOW_EVENTS_BY_TYPE).toHaveBeenCalled();
});
})
but i get the following response,
console.error ../../node_modules/vue/dist/vue.runtime.common.dev.js:1893 JestAssertionError: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
How do I go about testing chained async calls?
For reference we are using vue version 2.6.14
The Vuex actions are scheduled on microtasks after the component has mounted, but your first assertion is run before the first action has resolved.
One solution is to wait until the next micro tick:
const wrapper = shallowMount(MyComponent, { store, localVue })
await wrapper.vm.$nextTick() ๐
expect(actions[ACTION_TYPES.GET_WORKFLOW_TYPES]).toHaveBeenCalled()
await wrapper.vm.$nextTick() ๐
expect(actions[ACTION_TYPES.GET_WORKFLOW_EVENTS_BY_TYPE]).toHaveBeenCalled()
Alternatively, you could wait until the next macro tick at which point the current micro tasks would've already completed:
const wrapper = shallowMount(MyComponent, { store, localVue })
await new Promise(r => setTimeout(r)) ๐
expect(actions[ACTION_TYPES.GET_WORKFLOW_TYPES]).toHaveBeenCalled()
expect(actions[ACTION_TYPES.GET_WORKFLOW_EVENTS_BY_TYPE]).toHaveBeenCalled()