DEV Community

Cover image for React Testing Library — My Notes
Aditya Sharan
Aditya Sharan

Posted on

React Testing Library — My Notes

Some quick answers to common RTL-related questions.

Run tests

  • yarn run test

Where to usually place the tests?

  • Inside a test folder.

What is a common way to name tests?

  • Component.test.tsx

What is usually needed to import in test files?

import React from “react”; //React
import Counter from “../Counter”; //The component to test
import { render } from “@testing-library/react”;
Enter fullscreen mode Exit fullscreen mode

render is used for rendering the component in the virtual dom so you can then test what has been rendered. Due to this, it usually goes inside a beforeEach.

What would be an example of a basic test?

test(“header renders with correct test”, () => {
     const { getByTestId } = render(<Counter />);
     const headerEl = getByTestId(“header”);
     expect(headerEl.textContent).toBe(“My Counter”);
})
Enter fullscreen mode Exit fullscreen mode
  • The test's first argument would be the description.

  • The second argument would be a function with the actions of the tests.

  • expect is the function that actually does the test.

  • It is not a good practice to use getByTestId. This is just an example.

What would be a general description of testing with RTL?

  • You render a component.

  • Then you look and select elements inside the component.

  • Then you can:

  • Execute actions on the element (like clicks) and then verify the expected results.

  • Or just check the element to have the right values without executing any action before.

What would be an example of checking the right values in an element?

  • Expects the text content inside the element ‘headerEl’ to be the specific string “My Counter”.
expect(headerEl.textContent).toBe(“My Counter”);
Enter fullscreen mode Exit fullscreen mode

If you can’t find any way to select an element you want to, what is the last resource you can use?

getByTestId and the element need to be marked with the property:

data-testid
Enter fullscreen mode Exit fullscreen mode

What is useful for simulating actions?

  • The most used way is userEvent (because it is more similar to the user):
import userEvent from ‘@testing-library/user-event’; 
userEvent.dblClick(checkbox);
Enter fullscreen mode Exit fullscreen mode
  • But, fireEvent can also be used:
fireEvent.change(inputEl, {
     target: {
          value: “5”
     }
});
Enter fullscreen mode Exit fullscreen mode

What can you do if you expect something not to have a certain value?

  • With not.

expect(headerEl.textContent).not.toBe(“My Counter”);
How to output the code in the terminal?

screen.debug()
Enter fullscreen mode Exit fullscreen mode

That's all folks !!

Discussion (1)

Collapse
andrewbaisden profile image
Andrew Baisden

Keep up the good work!