← BACK

Beginners Guide to Testing in ReactJs
reactjsjavascriptjesttestingChrome Extension

Simple and complete React DOM testing utilities that encourage good testing practices.

Let's Create a simple react app using following commands in bash with assuming nodejs is installed already

 bash
npx create-react-app react-testing
cd react-testing
npm install --save-dev @testing-library/react // install react testing library which comes with jest-dom to access dom contents while testing
cd src mkdir components && cd components && touch Header.js && cd .. & cd ..

let's open Header.js component in Vs code or your favorite editor

 jsx
// Header.js
import React from 'react';
export default function Header({ text }) {
return <h2>{text}</h2>;
}

Now let's create a test file for this component

 jsx
// Header.test.js
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import Header from './Header';
it('renders', () => {
const { asFragment } = render(<Header text="Hello!" />);
expect(asFragment()).toMatchSnapshot(); // A snapshot is created with which it will compare the HTML generated
});

React testing library produces garbage wich can be cleaned up using

forEach(cleanup) [//cleanup](//cleanup) is imported from react testing library

 jsx
...
import {render,cleanup} from '@testing-library/react'
...
forEach(cleanup)
...

Now let's see how we can access the dom element and test the component

 jsx
// Header.js
....
return(
<h1 testId = "H1tag">
{text}
</h1>
);
 jsx
// Header.test.js
...
it('inserts H1 tag',()=>{
const { getByTestId, getByText } = render(<Header text="Hello!"/>
expect(getBytestId('h1tag')).toHaveContent('Hello!');
})

I hope you have understood the basic of using react testing library.

Thanks for reading