'How to test CSS properties defined inside a class with react testing library
I am trying to test CSS properties that i have defined inside a class in css, wing the react testing library. However I am unable to do so.
Adding the simplified snippets.
import React from "react";
import { render, screen } from "@testing-library/react";
import '@testing-library/jest-dom/extend-expect';
import styled from "styled-components";
const Title = styled.span`
display: none;
background: red;
`
test("testRender", () => {
render(
<div>
<Title>Test</Title>
</div>
)
const spanElement = screen.getByText("Test");
const elementStyle = window.getComputedStyle(spanElement);
expect(elementStyle.display).toBe('none');
});
The test fails at the expect statement. I have tried refactoring to traditional css, there also the test fails. In both cases, I have tested it manually and the styles are taking effect.
I also understand that we should not directly test CSS properties, but I have tried testing the visibility with toBeVisible(), but that only works if the display: none
is directly entered as a style, and not as part of a class.
This should be a very simple thing, that works out of the box, but I have been at it for some time now, without any luck.
Any help is appreciated.
Solution 1:[1]
I agree with @ourmaninamsterdam answer.
In addition, for checking appearance or disappearance of any element, you can also use .not.toBeInTheDocument
like so:
expect(screen.queryByText("Test")).not.toBeInTheDocument();
NOTE: You must use queryByText
instead of getByText
in this case since queryByText
wont throw an error if it doesn't find the element (it will return null).
Official docs Reference - https://testing-library.com/docs/guide-disappearance#nottobeinthedocument
Solution 2:[2]
You can use expect(screen.getByText("Test")).not.toBeVisible();
import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import styled from "styled-components";
it("does display", () => {
const Title = styled.span`
display: block;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).toBeVisible();
});
it("doesn't display", () => {
const Title = styled.span`
display: none;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).not.toBeVisible();
});
...see the sandbox: https://codesandbox.io/s/blazing-river-l6rn6?file=/App.test.js
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 | nishkaush |
Solution 2 |