Jest + SCSS @import 问题(CSS 模块)

4
我尝试着配置我的jest运行器,使其能够正确地处理我React应用程序中css模块中的scss @import语句。但不幸的是,每次运行测试脚本时都会出现错误。我尝试了StackOverflow类似问题上的不同解决方案,但它们并没有帮助到我。 我的错误示例: enter image description here 我的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"
]
};

transform.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'
    ],
});
1个回答

8
不要在模块名称映射正则表达式中使用空格。例如,使用以下方式:
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)) + ';';
  },
};

identity-obj-proxy并不是一个“常见”的文件映射器。它使用es6的Proxy将对象上访问的属性键作为字符串返回。 - Shalom Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接