This is a simple example but it will explain how the testing library works.
You can install react-testing-library by running
npm i @testing-library/react
or you can just run
npx create-react-app
to create a new React project, and you will have the library already installed.
This is our Button component:
import React, { useState } from "react"; export default function Button(){ const [clicked,isClicked]= useState(false); return( <> <button style={{background: clicked ? 'red' : 'green'}} onClick={e => isClicked(true)} data-testid="btn"> {clicked ? 'Clicked' : 'Click'} </button> </> ) }
Give the button a data-testid="btn", so we can access it later from the test file.
Now the test file:
First we have to import render and fireEvent.
render - to render into a container which is appended to document.body.
fireEvent- fire a DOM event.
Then we import the component we want to render.
import { render, fireEvent } from "@testing-library/react"; import Button from "./Button.js";
We use the beforeEach method to render components, elements, methods or something else before each test.
First we render the Button component, then we get the btn element by data-test-id.
let btn; beforeEach(()=>{ //execute before each test const component = render(<Button />); // render Button component btn = component.queryByTestId('btn'); // get the btn element from Button });
Each test has two arguments, a description of the test and a function.
1.Test
We are checking if the element btn exists.
test('Check if btn is rendering correctly',()=>{ expect(btn).toBeTruthy(); //check if btn exists in the component });
2.Test
We are checking if the button is changing it's background color on click. First we check if button has 'background: green' on render, then we fire a click event , and expect the button to have 'background: red';
test("Check if btn is changing it's color from green to red on click",()=>{ expect(btn).toHaveStyle('background: green'); // btn has the style of 'background:green' fireEvent.click(btn); // btn is clicked expect(btn).toHaveStyle('background: red'); //btn has the style of 'background:red' })
3. Test
We are checking if the text in button is changing on click.
First we check if the button's text-content is 'Click', then we fire a click event, and we expect the text-content to be 'Clicked'.
test("Check if btn says Clicked after it's clicked",()=>{ expect(btn.textContent).toBe('Click'); fireEvent.click(btn); expect(btn.textContent).toBe('Clicked'); })
Then we run
npm test
And if everything works fine, and all the test pass, we will see this:
Top comments (3)
Nice article! Havenโt used it but looks like the approach is common with other testing suits.
Thanks. Yeah, I mean, it's a basic example. But I plan on writing some more complicated examples, and tutorials on this topic.
Nice, I will wait to read them. Keep it up ๐ฅ