ReactDeveloper
ReactDeveloper

Reputation: 217

Testing styling in react testing library

I have a component, it has 2 divs with different background colours based on the pageIndex. I want to test this component when the pageIndex = 0 and when it is pageIndex = 1. The test succeed in both cases also it has to fail in the second one. What am i missing here?

export function FormSteps(props: FormStepsProps) {
  return (
    <div>
      <div
        style={{
          backgroundColor:
            props.pageIndex === 0
              ? "green"
              : "red",
        }}
      >
        <span>Step 1</span>
      </div>
      <div
        style={{
          backgroundColor:
            props.pageIndex === 1
              ? "red"
              : "green",
        }}
      >
        <span>Step 2</span>
      </div>
    </div>
  );
}
test("Page Index is 0", () => {
  render(<FormSteps pageIndex={0} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

Upvotes: 1

Views: 517

Answers (1)

poPaTheGuru
poPaTheGuru

Reputation: 1090

Based on your code, if page index === 0, then the first div would be green as you tested and second div should have backgroundColor: "red", and for page index === 1 would be otherwise. Here is your correct code to pass your tests:

test("Page Index is 0", () => {
  render(<FormSteps pageIndex={0} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "green"`);
});

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "red"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "red"`);
});

But if you want for your second test to fail, should be like this (this is what I understand from your question, that the second test should fail):

test("Page Index is 1", () => {
  render(<FormSteps pageIndex={1} />);

  const fieldStep1 = screen.getByText(/step 1/i);
  const fieldStep2 = screen.getByText(/step 2/i);

  expect(fieldStep1).toHaveStyle(`backgroundColor: "green"`);
  expect(fieldStep2).toHaveStyle(`backgroundColor: "green"`);
});

Upvotes: 1

Related Questions