如何用Jest测试导入SCSS的TSX文件?附配置及模块找不到报错
It looks like the issue stems from how Jest is configured to handle SCSS file imports—specifically, the regex patterns in your jest.config.js aren't correctly matching the SCSS files you're importing, so Jest isn't using the identity-obj-proxy mock as intended. Let's walk through the fixes step by step:
1. Verify Dependencies Are Installed
First, make sure you have identity-obj-proxy installed as a dev dependency (this package mocks CSS Modules for Jest):
npm install identity-obj-proxy --save-dev # or yarn add identity-obj-proxy --dev
2. Fix Regex Patterns in jest.config.js
Your current regex for matching SCSS files has an escape issue in the string format. In JavaScript strings, backslashes need to be doubled to be interpreted correctly in regex. Update your jest.config.js to use properly escaped patterns:
module.exports = { roots: ['<rootDir>/src'], collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}'], coverageDirectory: 'coverage', testEnvironment: 'jsdom', transform: { '.+\\.(ts|tsx)$': 'ts-jest' // Correctly escape backslash for regex }, transformIgnorePatterns: [ '^.+\\.scss$' // Ignore transforming SCSS files ], moduleNameMapper: { '^.+\\.scss$': 'identity-obj-proxy', // Match ALL .scss files, including relative paths '@/(.*)': '<rootDir>/src/$1' } }
Key Changes:
'^.+\\.scss$'replaces your original'\.scss$': This regex correctly matches any file ending with.scss(including relative paths like./login-styles.scss) by properly escaping the dot and using^.+to capture the full file path prefix.- The formatted config makes it easier to spot issues with pattern matching later.
3. Double-Check Import Paths in Your TSX Files
Ensure your SCSS import in the TSX file is correctly spelled and uses the right relative path. For example:
// Correct relative path match import styles from './login-styles.scss';
If the SCSS file is in a subdirectory, adjust the path accordingly (e.g., '../styles/login-styles.scss').
4. Confirm Webpack Compatibility
Your Webpack config looks correct for handling CSS Modules with SCSS, so once Jest is properly mocking the SCSS imports, your tests should run without module errors.
After making these changes, run your Jest tests again—this should resolve the "Cannot find module" error by directing Jest to use the identity-obj-proxy mock for all SCSS imports.
内容的提问来源于stack exchange,提问作者Rodrigo Manguinho

