Home > other >  How to unit-test "defineAsyncComponent" in Vue 3?
How to unit-test "defineAsyncComponent" in Vue 3?

Time:10-19

Say I want to unit test this utility function. I use Vue 3, but this code is in the "normal" js file, not sfc.

How could I do that?

function getDynamicComponent() {
  if (...)  {
    return defineAsyncComponent(() => import('../path/to/component-A.vue'))
  } else {
    return defineAsyncComponent(() => import('../path/to/component-B.vue'))
  }
}

In such cases I prefer to mock implementation of functions and check .toHaveBeenCalledWith(...). But I can't do that with import, right?

P.S. I'd be appreciated for Jest or Vitest syntax

CodePudding user response:

As a follow up to my comment, you can mock that function like that with jest :

let defineAsyncComponent = jest.fn()

let vueMock = {
    defineAsyncComponent
}

jest.mock('vue', () => {
    return vueMock;
})
import { defineAsyncComponent } from 'vue';

console.log(defineAsyncComponent._isMockFunction) // true

And then you can test that defineAsyncComponent was called :

expect(defineAsyncComponent).toHaveBeenCalled()

using toHaveBeenCalledWith will be tricky, because it uses toEqual, so your test will always fail

You could define an implementation on the defineAsyncComponent function to test the parameter :

let defineAsyncComponent = jest.fn().mockImplementation((fn) => {
    expect(typeof fn).toBe('function')
})

You could also call that function and check the return value, which is a promise, but at this point you are testing import() function so i don't think it adds value to your test :

let defineAsyncComponent = jest.fn().mockImplementation((fn) => {
    expect(typeof fn).toBe('function')
    expect(typeof fn().then).toBe('function')
})
  • Related