srk
srk

Reputation: 1901

How can I test css properties for a React component using react-testing-library?

The philosophy behind the react-testing-library makes sense to me, but I am struggling to apply it to css properties.

For example, let's say I have a simple toggle component that shows a different 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 should I test this component? I wrote the following test, which works for inline component styles, but fails when using 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("updates the background color when clicked",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});

Upvotes: 11

Views: 13919

Answers (2)

Devildude4427
Devildude4427

Reputation: 1094

So that's not what unit or integration test frameworks do. They only test logic.

If you want to test styling then you need an end-to-end/snapshot testing framework like Selenium.

Upvotes: 3

Priyankar Kumar
Priyankar Kumar

Reputation: 437

For making sure the styling is okay, I prefer snapshot testing. How about firing the event and taking snapshots for both states/cases. Here is what it would look like:

import React from 'react'
import {render} from '@testing-library/react'

 it('should take a snapshot when button is toggled', () => {
    const { asFragment } = render(<App />)
    // Fire the event 
    expect(asFragment(<App />)).toMatchSnapshot()
   })
});

Upvotes: 0

Related Questions