2

Is there a way to test a non inline style CSS color of the word 'Hello' in a jest?

.textStyle {
 color: red;
}

<p class="textStyle">Hello</p>

test('test text color', () => {
    const wrapper = mount(<React />);
    const p = wrapper.find('p').text();
    //insert code here
});

2 Answers 2

2

For that, you would use a regular getBy or findBy or any selectors and use a toHaveStyle accordingly

expect(getByTestId('elementId')).toHaveStyle('color: red')

You will also need to install jest-dom to have toHaveStyle available

Sign up to request clarification or add additional context in comments.

1 Comment

is this applicable for testing external css styles?
0

You might find some success with the window.getComputedStyle API. Calling this with an element gives you an object of that elements styles, which you can then verify have the correct values.

3 Comments

is this applicable for testing external css styles?
Yes, regardless of where the styles come from, this API will tell you which styles the element has applied to it right now. The same goes for the assertion suggested by Ryan Le, using jest-dom (it probably uses getComputedStyle in the background).
No, it doesn't work for non inline styles. I tested and it doesn't work when style is declared in scss file. stackoverflow.com/questions/75777333/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.