You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest测试导入SCSS的TSX文件?附配置及模块找不到报错

Fixing "Cannot find module './login-styles.scss'" in Jest Tests for TSX Files

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:53:13