【问题标题】:webpack require non-js content in jest unit-testswebpack 在开玩笑的单元测试中需要非 js 内容
【发布时间】:2017-03-11 04:17:42
【问题描述】:

最近我将我的一个项目转换为 webpack & babel。它由敲除组件制成。

我在运行单元测试时遇到了问题。如果我在 tests 文件夹中有一个文件,例如

import component from '../custom-options';

test('adds 1 + 2 to equal 3', () => {
  expect(3).toBe(3);
});

问题是该组件是一个模块,它具有排序要求

var htmlString = require('./custom-options.html');

当我尝试运行网站本身时,它运行良好,因为原始加载程序已针对此要求进行了配置。但是,当我开玩笑时,测试输出:

 custom-options.html:1
 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){?<div id="custom-options-containe" class="mod--custom-options">
                                                                                          ^
SyntaxError: Unexpected token <

  at transformAndBuildScript (node_modules\jest-cli\node_modules\jest-runtime\build\transform.js:284:10)
  at custom-options.js:13:38
  at Object.<anonymous> (custom-options.js:93:3)

知道为什么会这样吗?我认为 jest 是错误的,但我尝试用 Ava 代替它,结果是一样的。我开始认为这是一个 babel 问题。

我正在使用 babel-jest 预处理器运行 jest。

【问题讨论】:

    标签: webpack babeljs jestjs babel-jest


    【解决方案1】:

    您也可以使用jest-raw-loader 来模仿webpack's raw-loader 的动作。 您需要将其设置为transform,并确保包含默认的babel-jest 转换条目。

    "jest": {
      "transform": {
        "\\.js$": "babel-jest",
        "\\.(html|xml|txt)$": "jest-raw-loader"
      }
    }
    

    【讨论】:

    • 是的。为 js 文件添加默认转换是原始的。请注意,上面的配置是 jest.config.js 文件的一部分。
    【解决方案2】:

    您可以在 package.json 的 jest 设置中为所有非 JS 文件创建一个全局模拟,如下所示:

    "jest": {
      "moduleNameMapper": {
        "^.+\\.html$": "<rootDir>/__mocks__/htmlMock.js"
      }
    }
    

    然后在项目根目录的__mocks__ 文件夹中创建文件htmlMock.js,内容如下:

    module.exports = 'test-file-stub';
    

    更多信息请查看here

    如果你想为每个测试用例做一个特殊的模拟,你也可以像这样在你的测试中模拟文件:

    jest.mock('path/from/test/to/custom-options.html', ()=> 'test-file-stub');
    

    请注意,路径是相对于测试文件而不是相对于您要测试的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 2018-09-10
      • 2015-01-27
      • 2021-02-05
      • 1970-01-01
      • 2021-05-09
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多