【问题标题】:require.context not a function when trying to run Mocha tests尝试运行 Mocha 测试时 require.context 不是函数
【发布时间】:2023-03-08 21:05:01
【问题描述】:

我正在尝试使用Mocha.js + JSDOM 框架运行测试,但我无法让Mocha 启动。这是在使用Vue.js 库测试React 应用程序的过程中。我不断收到以下错误:

var req = require.context('./', false, /\.vue$/);
TypeError: require.context is not a function

有问题的代码是:

let req = require.context('./', false, /\.vue$/);
components.forEach(function (component) {
    try {
        let filePath = './' + component + '.vue';
        let injected = inject(req(filePath));
        Vue.component(getComponentName(component), injected);

        let appComponent = {
            name: injected.name,
            props: {
                autocompletion: {
                    metadata: getComponentName('template'),
                    score: xTemplatesScore,
                    attributes: injected.props || []
                }
            }
        };

        appComponents.push(appComponent);

    } catch (err) {
        console.log(err);
        console.error('Vue file was not found for component:' + component + '. Please rename your files accordingly ( component-name.vue )');
    }

有没有办法解决这个问题并真正让Mocha 启动?或者require.context有合适的替代品吗?我试图用纯字符串连接和香草require 重做它,但这一直告诉我找不到任何Vue 模块。

【问题讨论】:

    标签: javascript reactjs webpack mocha.js vue.js


    【解决方案1】:

    require.context 是 webpack 的一个方法。您的测试必须先捆绑,然后才能运行。

    通常,您会为测试创建一个单独的 webpack 配置文件。然后,您将使用 webpack 创建一个测试包,然后在此包上运行 Mocha。或者,您可以在 webpack 测试配置文件中使用 mocha-loader 并让测试作为捆绑过程的一部分运行。

    更多信息请见webpack documentation on testing

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      相关资源
      最近更新 更多