Mindaugas
Mindaugas

Reputation: 415

Mocking css modules in jest

In my test I am importing a jsx file which imports css:

import styles from '~/shared/styles/Profile.css';

I am trying to mock all css files with identity-obj-proxy as I am using css-modules. It doesn't seem to work though.

Package.json

"jest": {
    "moduleNameMapper":{
      "\\.(css|less)$": "identity-obj-proxy"
    },

I also tried:

"jest": {
    "moduleNameMapper":{
      "^.+\\.(css|less)$": "<rootDir>/config/CSSStub.js"
    },

while creating CSSStub.css

module.exports = {};

No effect - still the same parsing css error from Jest.

What am I doing wrong?

Upvotes: 6

Views: 6037

Answers (3)

Seiya
Seiya

Reputation: 143

identity-obj-proxy doesn't work with default export.

Comments in this issue helps me. https://github.com/keyz/identity-obj-proxy/issues/8

Especially joaovieira's comment seems good.

Here is alternative implementation for identity-obj-proxy, that works with default export.

https://github.com/keyz/identity-obj-proxy/issues/8#issuecomment-430241345

Upvotes: 2

willy
willy

Reputation: 9

this solved the problem for me

moduleNameMapper: {
    '^.+\\.(sass|css)$': '<rootDir>/__mocks__/styles.js'
  }

error:

    Cannot find module 'myStyles.module.sass' from 'myComponent.js'

Upvotes: 0

mfakhrusy
mfakhrusy

Reputation: 1208

I don't know if you're still having this since the question is around 6 months old but I think you should name your file CSSStub.js instead of CSSStub.css.

Upvotes: 0

Related Questions