Currently, I am working on a React project that utilizes SASS (SCSS syntax) for styling and Jest for unit testing. I've run into some difficulties when it comes to testing the styling in my project. To illustrate this issue, let's consider the following example:
Within component.js (which imports an external stylesheet)...
const Component = () => {
return (
<div className="greeting">Hello</div>
)
}
In my .scss file...
.greeting {
background-color: red;
}
For my test file...
test('background color should be red', () => {
render(<Component />);
expect(screen.getByText('Hello')).toHaveStyle('background-color: red');
})
The test fails with the following message:
expect(element).toHaveStyle()
- Expected
- background-color: red;
However, if I choose to use inline styling (
<div style={{backgroundColor: red}}>Hello</div>
), the test passes successfully.
I would appreciate hearing from anyone who has encountered this particular issue. Additionally, I'm curious to learn about different approaches people have taken for testing styling in Jest, especially when styles are stored in a separate .scss file.
For my tests, I rely on screen
from @testing-library/dom
and render
from @testing-library/react
.