gpt4 book ai didi

webpack 在 Jest 单元测试中需要非 js 内容

转载 作者:行者123 更新时间:2023-12-04 23:16:26 24 4
gpt4 key购买 nike

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

我在运行单元测试时遇到了问题。如果我在 中有一个文件测试 像这样的文件夹

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

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

问题是该组件是一个需要排序的模块
var htmlString = require('./custom-options.html');

当我尝试运行网站本身时,它运行良好,因为原始加载程序是为此要求配置的。但是,当我开 Jest 时,测试输出:
 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。

最佳答案

您可以在 package.json 中的开 Jest 设置中为所有非 JS 文件创建一个全局模拟。像这样:

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

然后创建文件 htmlMock.js__mocks__项目根目录中的文件夹,其中包含以下内容:
module.exports = 'test-file-stub';

欲了解更多信息,请查看 here

如果你想为每个测试用例做一个特殊的模拟,你也可以在你的测试中模拟文件,如下所示:
jest.mock('path/from/test/to/custom-options.html', ()=> 'test-file-stub');

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

关于webpack 在 Jest 单元测试中需要非 js 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com