DEV Community

Kudzai Murimi
Kudzai Murimi

Posted on • Updated on

Test React components in few steps: Unit tests

The main reason why we need to test is to test whether the app behaves as expected on not. Apps may have some errors which we may not discover but using react test library in the best solution.

React Testing is grouped into 3 categories.

1. Unit Test

  • whereby we test a single a component.

2. Integration test

  • whereby we test multiple components

3. End to End test (E2E)

  • where we test the whole App from Frontend-Backend.

Let's dive into :

Unit test

  1. Select a component you would like to test.
  2. Copy and paste the name of that component. In my case the name of the my component is PayButton The name of the file is PayButton.jsx and after pasting I will rename the file to PayButton.test.js
  3. You need to add the description of what you what to test in that test file(PayButton.test.js).
  4. You need to import the component into that test file too.

Below is how my test file looks like PayButton.test.js

import {render, screen} from "@testing-library/react"
import PayButton from "./PayButton"

test('on initial render, the pay button is disabled,', () =>{

render(<PayButton/>);

screen.debug();
}
)

Enter fullscreen mode Exit fullscreen mode

Once you are done, you now go to terminal and run the command

npm test
Enter fullscreen mode Exit fullscreen mode

if you are using npm

yarn test
Enter fullscreen mode Exit fullscreen mode

if you are using yarn.

You can also fix the errors in that test file too in that test file depending on the errors you are seeing.

Let's move on to Integration testing

Top comments (0)