Search code examples
vue.jspiniavitest

Mock async action in Pinia


I have a simple component that triggers an async Pinia-action (on button click) followed by a router.push().

Now I try to unit test that behavior, specific I'm expecting the router.push. But somehow it does not call, unless I remove the call (or the await) to the async action.

Component

async function resolve() {
    await store.resolveId() // it works if I remove this line (or remove the await)
    if (store.apiUrl) {
        router.push('/')
    }
}

Test

        it('should redirect to root', () => {
            const wrapper = mount(SelectTenant, {
                global: {
                    plugins: [createTestingPinia()]
                }
            })

            wrapper.find('#resolveButton').trigger('click')

            expect(useRouter().push).toHaveBeenCalled() // this fails
        })

Solution

  • Ok... I found a solution (or a workaround, don't know):

    import { mount, flushPromises } from '@vue/test-utils'
    // ...
    await flushPromises()
    expect(useRouter().push).toHaveBeenCalled() // OK