如何在 Jest 测试中使用我的 webpack 的 html-loader 导入? [英] How can I use my webpack's html-loader imports in Jest tests?
问题描述
我刚刚开始使用 Jest 测试框架,虽然直接的单元测试工作正常,但我在测试其模块中的任何组件(通过 babel+webpack 的 ES 模块)需要 HTML 文件时遇到了大量问题.
I am just getting started with the Jest test framework and while straight up unit tests work fine, I am having massive issues testing any component that in its module (ES module via babel+webpack) requires a HTML file.
这是一个例子:
import './errorHandler.scss';
import template from './errorHandler.tmpl';
class ErrorHandler {
...
我正在加载我在 Jest 的 package.json
配置中设置的特定于组件的 SCSS 文件以返回一个空对象,但是当 Jest 尝试从 './errorHandler 运行 import 模板时.tmpl';
断行说:
I am loading the component specific SCSS file which I have set in Jest's package.json
config to return an empty object but when Jest tries to run the import template from './errorHandler.tmpl';
line it breaks saying:
/Users/jannis/Sites/my-app/src/scripts/errorHandler/errorHandler.tmpl.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<div class="overlay--top">
^
SyntaxError: Unexpected token <
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
我在 package.json
中的 Jest 配置如下:
My Jest config from package.json
is as follows:
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/test/setupFile.js",
"moduleDirectories": ["node_modules"],
"moduleFileExtensions": ["js", "json", "html", "scss"],
"moduleNameMapper": {
"^.+\.scss$": "<rootDir>/test/styleMock.js"
}
}
似乎 webpack html-loader
与 Jest 无法正常工作,但我找不到任何解决方案.
It seems that the webpack html-loader
is not working correctly with Jest but I can't find any solution on how to fix this.
有谁知道我如何让这些 html-loader
import
在我的测试中工作?他们加载了我的 lodash 模板标记,而我有时不想在我的 .js
文件中包含这些大量的 HTML 块,这样我就可以省略 import template from x
部分.
Does anyone know how I can make these html-loader
import
s work in my tests? They load my lodash template markup and i'd rather not have these at times massive HTML chunks in my .js
file so i can omit the import template from x
part.
PS:这不是一个 React 项目,只是普通的 webpack、babel、es6.
PS: This is not a react project, just plain webpack, babel, es6.
推荐答案
我最近遇到了这个具体问题并创建了自己的 transform preprocesser 将解决它.这是我的设置:
I encountered this specific problem recently and creating your own transform preprocesser will solve it. This was my set up:
package.json
"jest": {
"moduleFileExtensions": [
"js",
"html"
],
"transform": {
"^.+\.js$": "babel-jest",
"^.+\.html$": "<rootDir>/test/utils/htmlLoader.js"
}
}
注意:babel-jest 通常默认包含在内,但如果您指定自定义转换预处理器,您似乎必须手动包含它.
NOTE: babel-jest is normally included by default, but if you specify a custom transform preprocessor, you seem to have to include it manually.
test/utils/htmlLoader.js:
const htmlLoader = require('html-loader');
module.exports = {
process(src, filename, config, options) {
return htmlLoader(src);
}
}
这篇关于如何在 Jest 测试中使用我的 webpack 的 html-loader 导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!