Nuxt + Jest : unknow custom element if "components" is not set

Viewed 839

One of the thing I like in Nuxt is not having to include all used components. But this is not working with Jest.

I started from the default nuxt app with jest. I added a custom element in 'Logo.Vue' like this :

<template>
  <div class="VueToNuxtLogo">
      <MyComponent />
  </div>
</template>

I added the component file 'MyComponent.vue':

<template>
    <span>My great component<span>
</template>

When I run the app, I can see MyComponent. But the 'Logo.spec.js' test return this error : [Vue warn]: Unknown custom element: <MyComponent> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

If I include the component like this, test is OK.

import MyComponent from './MyComponent'
export default {
  components: { MyComponent }
}

Is there any way to automatically import components using Jest like Nuxt do ?

1 Answers

So for now it is not possible to do so, I found this issue on github : Question: auto scan feature causes some tests failure #58

But it is not that hard to do it manually, I add this function in a 'tests/beforeAllTests.js' file:

import path from 'path';
import glob from 'glob';
import Vue from 'vue';

export default function beforeAllTests () {
    // Automatically register all components
    const fileComponents = glob.sync(path.join(__dirname, '../components/**/*.vue'));
    for (const file of fileComponents) {
        const name = file.match(/(\w*)\.vue$/)[1];
        Vue.component(name, require(file).default);
    }
}

Add I call it before each test

import beforeAllTests from '~/tests/beforeAllTests';
describe('Some tests', () => {

    beforeAll(async () => {
        beforeAllTests();
    });
Related