首页 > 解决方案 > 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'
    ],
});

标签: reactjssassjestjsbabeljscss-modules

解决方案


不要在模块名称映射器正则表达式中使用空格。例如,而不是:

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)) + ';';
  },
};

推荐阅读