Search code examples
vue.jsvuejs2vue-test-utils

Lazy loading component globally. Error on testing


I'm lazy-loading a component globally like this:

Vue.component(
    'TheDialog',
    () => import(/* webpackChunkName: "theDialog" */  '@/components/TheDialog')
)

Works fine, but when I run tests on another component, which contain TheDialog as a child component, I get this warning:

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Also, I have the same error when importing a global component without lazy-loading:

import TheDialog from '@/components/TheDialog'

Vue.component(
    'TheDialog', TheDialog
)

Does somebody know the problem?


Solution

  • Based on vuejs/vue-test-utils Issue#1116, the globally registered component would still need to be registered when using shallowMount.

    One solution is to globally register the component on a localVue instance:

    const localVue = createLocalVue()
    localVue.component('TheDialog', TheDialog)
    
    shallowMount(MyComponent, { localVue })
    

    or you could explicitly stub it upon mounting:

    shallowMount(MyComponent, { stubs: ['TheDialog'] })
    

    Another solution is to move your global component registrations (e.g., from main.js) into a separate file that could also be imported in your tests.