4

From what I understand about testing-library-react, one should avoid using container.querySelector because the whole point of the testing library is to test mostly "as the user does." I'm on board with this, but what is the proper way, if any, to test that a class name (for actual styling purposes) is applied to a <p> tag for example?

In my specific example, the text should be one of three colors, based on a priority. So I'd like to test to ensure that not only does the correct text exist, but it should up in the correct color.

const SomeComponent = ({ priority }) => {
  const priorityClass = priorityEvaluator(priority); # returns class with "color: red, green, or yellow"
  return (
    <p className={priorityClass}>Some text</p>
  )
)}

In the test:

test("something", () => async {
  const { findByText } = render(<SomeComponent />);
  expect(findByText("Some text").toBeTruthy();
  # assert text is the proper color?
})

Is the preferred way to use jest-dom's toHaveStyle/toHaveClass and target the element by the testid data attribute? Or is there a better way?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user3281384
  • 511
  • 1
  • 7
  • 17
  • https://github.com/testing-library/jest-dom#tohaveclass? – jonrsharpe Oct 27 '19 at 19:39
  • 2
    Possible duplicate of [How to test a className with Jest and React testing library](https://stackoverflow.com/questions/53389956/how-to-test-a-classname-with-jest-and-react-testing-library) – Gio Polvara Oct 28 '19 at 08:46

0 Answers0