webpack 在开玩笑的单元测试中需要非 js 内容
webpack require non-js content in jest unit-tests
最近我将我的一个项目转换为 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)
知道为什么会这样吗?我认为开玩笑是错误的,但我尝试用 Ava 代替它,结果是一样的。我开始认为这是一个 babel 问题。
我正在 运行使用 babel-jest 预处理器开玩笑。
您可以在 package.json
中的开玩笑设置中为所有 none 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');
注意路径是相对于测试文件而不是你要测试的文件。
您也可以使用jest-raw-loader
to mimic the action of webpack's raw-loader
。
您需要将其设置为 transform
,并确保包括默认的 babel-jest
转换条目。
"jest": {
"transform": {
"\.js$": "babel-jest",
"\.(html|xml|txt)$": "jest-raw-loader"
}
}
最近我将我的一个项目转换为 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)
知道为什么会这样吗?我认为开玩笑是错误的,但我尝试用 Ava 代替它,结果是一样的。我开始认为这是一个 babel 问题。
我正在 运行使用 babel-jest 预处理器开玩笑。
您可以在 package.json
中的开玩笑设置中为所有 none 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');
注意路径是相对于测试文件而不是你要测试的文件。
您也可以使用jest-raw-loader
to mimic the action of webpack's raw-loader
。
您需要将其设置为 transform
,并确保包括默认的 babel-jest
转换条目。
"jest": {
"transform": {
"\.js$": "babel-jest",
"\.(html|xml|txt)$": "jest-raw-loader"
}
}