I'm working on a React project that uses SASS (SCSS syntax) for styling, along with Jest for unit tests. I'm having trouble testing styling in my project. Here's a simple example:
In component.js (which imports a separate stylesheet)...
const Component = () => {
return (
<div className="greeting">Hello</div>
)
}
In my .scss file...
.greeting {
background-color: red;
}
In my test file...
test('background color should be red', () => {
render(<Component />);
expect(screen.getByText('Hello')).toHaveStyle('background-color: red');
})
The test fails with:
expect(element).toHaveStyle()
- Expected
- background-color: red;
However, if I use inline styling (<div style={{backgroundColor: red}}>Hello</div>
), the test passes.
Has anyone encountered this issue? I'm also wondering other people's approaches to testing styling in Jest (particularly when your styles are kept in a separate .scss file)
I am utilizing screen
from @testing-library/dom
and render
from @testing-library/react
for my tests.
I agree with Dominik. Jest is good for testing properties of your rendered HTML. Unless the styling is within the HTML (inline styling), Jest will not see it (as you have pointed out). The deepest you could test without in-lining the styles is to verify that it has a proper class name.
Maybe a test framework that runs in a browser like Cypress? Have a read of visual testing with Cypress.