x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    React Jest tutorial

    In this tutorial, we will see how to configure unit tests for react and then show how to write Jest test to unit test react code. React based applications use Jest as unit test runner which is based on Node.js.

    Writing a basic Jest test

    First let us create a new react app using this command npx create-react-app helloworld. When you create a new app using npx command, it will also create configuration for unit tests. Note that setupTests.js is created which contains the basic setup for Jest tests.

    import logo from './logo.svg';
    import './App.css';
    
    function App() {
      return (
        <div className="App">
          <h1>Hello, world!</h1>
        </div>
      );
    }
    
    export default App;
    

    Now update App.test.js which will render the App and verify if the expected text is displayed on page.

    import { render, screen } from '@testing-library/react';
    import App from './App';
    
    test('renders learn react link', () => {
      render(<App />);
      const linkElement = screen.getByText("Hello, world!");
      expect(linkElement).toBeInTheDocument();
    });

    If you run npm test, it will run all the jest tests.


    Show hide div

    Show hide div












    Testing events using Jest

    Create Hello.js which just displays a label with a button, when user clicks on this button, text displayed will change.

    import { useState } from "react";
    
    const Hello = () => {
        const [changedText, setChangedText] = useState(false);
        const changedTextHandler = () => {
            setChangedText(true);
        };
    
        return (
            <div>
                <h2>Hello World!</h2>
                {!changedText && <p>ice to see you!</p>}
                {changedText && <p>Text Changed!</p>}
                <button onClick={changedTextHandler}>Change Text!</button>
            </div>
        );
    };
    
    export default Hello

    Create Hello.test.js which will test whether button click works. When user clicks on 'Change Text!' button, text displayed will change to 'Text Changed!'. We can simulate button click by using fireEvent.

    import { render, screen, fireEvent} from "@testing-library/react";
    import Hello from "./Hello";
    
    test('renders text changed! as a text when user clicks on button', () => {
      render(<Hello />);
    
      const buttonElement = screen.getByRole('button');
      fireEvent.click(buttonElement);
      const element = screen.getByText('Text Changed!', {exact: false});
      expect(element).toBeInTheDocument();
    });

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This