【问题标题】:Nuxt + Jest : unknow custom element if "components" is not setNuxt + Jest:未设置“组件”的未知自定义元素
【发布时间】:2021-03-07 09:23:42
【问题描述】:

我喜欢 Nuxt 的一件事是不必包含所有使用过的组件。但这不适用于 Jest。

我从默认的 nuxt 应用开始玩笑。我在“Logo.Vue”中添加了一个自定义元素,如下所示:

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

我添加了组件文件'MyComponent.vue':

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

当我运行应用程序时,我可以看到 MyComponent。 但“Logo.spec.js”测试返回此错误:[Vue warn]: Unknown custom element: &lt;MyComponent&gt; - did you register the component correctly? For recursive components, make sure to provide the "name" option.

如果我包含这样的组件,测试就可以了。

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

有没有办法像 Nuxt 那样使用 Jest 自动导入组件?

【问题讨论】:

    标签: jestjs nuxt.js


    【解决方案1】:

    所以目前还不能这样做,我在github上发现了这个问题:Question: auto scan feature causes some tests failure #58

    但手动操作并不难,我在 'tests/beforeAllTests.js' 文件中添加了这个函数:

    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);
        }
    }
    

    添加我在每次测试之前调用它

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

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2020-09-01
      • 2020-01-01
      • 2018-09-14
      • 2020-02-02
      • 2018-12-23
      • 2019-11-22
      • 2013-05-22
      • 2017-08-05
      相关资源
      最近更新 更多