• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

194
Views
unit testing vue component

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

about 3 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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()

demo

about 3 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
ยฉ 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error