Client side

Contents

This chapter covers setting up and running client-side tests.

Node modules

For this example, we’re going to need some more modules.

npm install --save-dev react react-dom react-test-renderer @types/react

Configuration

Since we are going to write a tsx file, we need to make sure the tsconfig.json file includes the jsx option.

src/main/resources/assets/tsconfig.json
{
  "compilerOptions": {
    "esModuleInterop": true,
    "jsx": "react",
    // other compilerOptions...
  },
  // extends, files, include, exclude...
}

Source code

Here is the React component we will be testing:

src/main/resources/assets/HelloWorld.tsx
import React from 'react';


export const HelloWorld = () => {
    return <h1>Hello, World!</h1>;
}

Test

Adding the following test will let us test the component:

src/jest/client/HelloWorld.test.tsx
import {
    describe,
    expect,
    test as it
} from '@jest/globals';
import React from 'react';
import renderer from 'react-test-renderer';
import {HelloWorld} from '/assets/HelloWorld';


describe('HelloWorld', () => {
    it('should render', () => {
        const component = renderer.create(
            <HelloWorld/>,
          );
        const tree = component.toJSON();
        expect(tree).toEqual({ type: 'h1', props: {}, children: [ 'Hello, World!' ] });
    });
});

Output

Run the test, and see what happens:

npm run cov src/jest/client/HelloWorld.test.tsx
> tutorial-jest@1.0.0 test
> jest --no-cache --coverage src/jest/client/HelloWorld.test.tsx

 PASS   CLIENT  src/jest/client/HelloWorld.test.tsx
  HelloWorld
    ✓ should render (11 ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files       |     100 |      100 |     100 |     100 |
 HelloWorld.tsx |     100 |      100 |     100 |     100 |
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.1 s
Ran all test suites matching /src\/jest\/client\/HelloWorld.test.tsx/i.

Summary

You have now learned how to write a test for a React component using Jest and React Test Renderer.

Now that we have some tests, it may be useful to store coverage reports in a tool that can show progress over time. One such tool is Codecov.

The following chapter will show you how to integrate Codecov with your project.


Contents

Contents