I understand the philosophy behind the react-testing-library, but I am having difficulty implementing it with CSS properties.
For instance, consider a basic toggle component that changes its background color when clicked:
import React, { useState } from "react";
import "./Toggle.css";
const Toggle = () => {
const [ selected, setSelected ] = useState(false);
return (
<div className={selected ? "on" : "off"} onClick={() => setSelected(!selected)}>
{selected ? "On" : "Off"}
</div>
);
}
export default Toggle;
.on {
background-color: green;
}
.off {
background-color: red;
}
How can I test this component? I have written a test below, which works for inline styles, but not for css classes as shown above.
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";
const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;
describe("Toggle", () => {
it("changes the background color upon clicking", () => {
render(<Toggle />);
fireEvent.click(screen.getByText("Off"));
expect(backgroundColor(screen.getByText("On"))).toBe("green");
});
});