techStackGuru

Testing library Jest

JEST is a testing library inspired by the way unit tests are written in JavaScript. Its designed for ease of use, but can also be used to integrate synchronous and asynchronous non-trivial code as test data.

Installing and Running Jest

First, create a React app


npx create-react-app react-jest-tutorial

Now, install React Testing Library


npm install --save-dev @testing-library/react

Import the folder into Visual Studio Code.

Now open Explorer in VS code and you can see App.test.js file is created.


App.js file


function App() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer">

            Learn React

          </a>
        </header>
      </div>
    );
  }

App.test.js file


test('renders learn react link', () => {
    render(<App />);
    const linkElement = screen.getByText(/learn react/i);
    expect(linkElement).toBeInTheDocument();
  });

 // or

 test('renders learn react link', () => {
    render(<App />);
    expect(screen.getByText(/learn react/i)).toBeInTheDocument(); 
  });
 

To Run test we use below command


npm test
jest-test

Above you can see 1 Passed test. This test is checking whether Learn React text available in App.js file for not.


Example - Test Fail

Lets rename text in the file to Learn Java and test the result.

App.js file


function App() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer">

            Learn Java

          </a>
        </header>
      </div>
    );
  }

Run the test


npm test
jest-test

This time test is searching for Learn React text and that text is not found so it got failed.


next-button