JEST keeps trying to parse CSS module even after using identity-obj-proxy

Viewed 492

I am using css modules with sass in a React application. I used identity-obj-proxy but it is not working for css modules, it works for normal scss files. I have jest configuration setup in jest.config.js and I am sure that it is being read correctly.

App.js

import scss from '@project/styles/js-variables.scss';

jest.config.js

module.exports = {
  verbose: true,
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@app(.*)$': '<rootDir>/app$1',
    '^@project(.*)$': '<rootDir>/app/projects/NBK$1',
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/testing/mocks/fileMock.js',
  },
  transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$'],
};

js-variables.scss

@import '~@project/styles/colors';
@import '~@project/styles/variables';

:export {
  mainColor: $main-color;
  bodyColor: $body-black;
  backgroundColor: $dropdown-background-color;
}

I have tried everything, using transform and custom mappers but nothing is working. Any help is appreciated.

1 Answers

In this case you should move '\\.(scss|sass|css)$': 'identity-obj-proxy' to the top entry of your moduleNameMapper object. As the ordering matters, your .scss file import is being matched against '^@project(.*)$' first.

moduleNameMapper: {
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/testing/mocks/fileMock.js',
    '^@app(.*)$': '<rootDir>/app$1',
    '^@project(.*)$': '<rootDir>/app/projects/NBK$1',
}
Related