'toHaveStyles not working with module.css styles using React testing library with Jest

I have this component for which I am writing test case using react testing library I am facing an issue with styles when the styles is imported from .module.css file but works fine when I use styled components(style.js)

Demo.js

import styles from 'components/Demo/demo.module.css'
const Demo = () => {
  return (
    <div>
      <p className={styles.newText} data-testid="closeIcon">
        hello
      </p>
    </div>
  )
}
export default Demo

Demo.test.js

import Demo from 'components/Demo/Demo'
import { render, screen } from '@testing-library/react'
describe('Demo Component', () => {
  it('Component renders without crashing', () => {
    render(<Demo />)
    expect(screen.getByTestId('closeIcon')).toHaveStyle({ background: 'red' })
  })
})

demo.module.css

.newText {
  background-color: red;
}

But when I use styles.js it works -> styles.js

import { makeStyles } from '@material-ui/core/styles'
const useStyles = makeStyles((theme) => ({
  icon: {
    backgroundColor: 'red',
  },
}))
export default useStyles


Solution 1:[1]

Could you please tell us what your jest.config.js looks like?

As a general rule, SASS and CSS are often excluded from jest because of errors.

In the following example, identity-obj-proxy is used to take the className of the style, but the application of the style itself is mock.

Syntax Error when test component with SASS file imported

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tubone