reactjs - Jest + SCSS @import 问题(css 模块)
问题描述
我试图设置我的 jest runner 以正常使用 scss@impport
语句(在我的 React 应用程序中的 css 模块内)。但不幸的是,每次运行测试脚本时都会出错。我尝试了 StackOverflow 类似票证的不同解决方案,但对我没有帮助。
我的错误示例:
我的 jest.config.js:
module.exports = {
transform: {
"^.+\\.(jsx?|tsx?)$": "<rootDir>/.jest/transform.ts",
},
testURL: 'http://localhost:6006/',
testRegex: "((\\.|/)(test|spec))\\.(jsx?|tsx?)$",
preset: 'jest-puppeteer',
moduleFileExtensions: [
"scss",
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
'\\.(jpg | ico | jpeg | png | gif | eot | otf | webp | svg | ttf | woff | woff2 | mp4 | webm | wav | mp3 | m4a | aac | oga)$ ': '<rootDir>/__mocks__/fileMock.js',
'\\.(css | scss)$': 'identity-obj-proxy'
},
transformIgnorePatterns: ['<rootDir>/node_modules'],
setupFilesAfterEnv: [
"<rootDir>/.jest/register-context.ts",
"<rootDir>/.storybook/setupTests.ts"
]
};
转换.ts 文件:
module.exports = require('babel-jest').createTransformer({
presets: [
['@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }],
'@babel/preset-react',
'@babel/preset-typescript',
],
plugins: [
'require-context-hook',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-transform-modules-commonjs'
],
});
解决方案
不要在模块名称映射器正则表达式中使用空格。例如,而不是:
moduleNameMapper: {
'\\.(css | scss)$': 'identity-obj-proxy'
},
用这个:
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy'
},
我从来没有使用过identity-obj-proxy,我没有测试过它,但正如我所读到的,它完成了一个与普通文件映射器类似的任务,如下所示:
const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
},
};
推荐阅读
- webstorm - 如果输入来自 WebStorm 中的 Web,如何在控制台中查看输出
- java - 如果不存在则根据点字符串包名创建目录
- python - 我如何阅读特定的一行以及该行下的另外 7 行
- c++ - 读取函数会影响文件的获取指针吗?
- gcc - 如何在 rustc 中使用 gcc 标志
- javascript - 根据位置替换 url 中的 GET 参数(正则表达式)
- mysql - Vue JS 组件中 MySQL 的嵌套 JSON 总和
- asp.net - 如何在 ASP.NET 中正确发布 formcollection?
- ruby-on-rails - “rails new blog”的 Rails 基本安装问题
- python - Django - 转换 datetime.date 元组