Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test styling using Jest

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.

like image 210
Eric Avatar asked Nov 02 '20 00:11

Eric


People also ask

Is Jest enough for testing?

Despite what many may think, Jest is not just a test runner—it is a complete testing framework that has brought testing to another level. It's powerful but easy to use, so give it a try.

Can I use Jest without Enzyme?

Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it. An enzyme can also be used without Jest, but we need any other test runner paired with it. Jest:- Jest as a test runner, assertion library, and mocking library.


2 Answers

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.

like image 94
ckesplin Avatar answered Oct 23 '22 21:10

ckesplin


You can use window.getComputedStyle() to access the final result of all your styling, even those in classes.

In your case, in order to test what the background color the div element ends up being you would write:

test('background color should be red', () => {
    render(<Component />);

    const element = screen.getByText('Hello');
    const styles = getComputedStyle(element);

    expect(styles.backgroundColor).toBe('red');
})
like image 7
Vintr Avatar answered Oct 23 '22 22:10

Vintr