React Unit Testing using @testing-library/react

Erba AfidotamaErba Afidotama
1 min read

Example component code:

import {useState} from 'react';

const Text = ({text}) => {
    const [state, setState]= useState(0);

    const add  = () => {
        setState(state+1)
    };

    return (
        <div>
            <h1>Hello World</h1>
            <h2>Hello {text}</h2>
            <h2>Count {state}</h2>
            <button role="button" onClick={add}>Increase</button>
        </div>
    );
};

export default Text;

You can testing your element exist using text from your element. example testing code:

import {
  render
} from "@testing-library/react";

test('check button increse exist', ()=> {
    const { getByText } = render(<Text />);
    const button = getByText("Increase");
    expect(button).toBeTruthy()
});
0
Subscribe to my newsletter

Read articles from Erba Afidotama directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Erba Afidotama
Erba Afidotama

For now, im a website developer using React, NextJS, or Vue. Im still learning other framework like Svelte and Qwik, and learning mobile development Flutter.