Unit testing and React

If you’ve created a React application using yarn, you’ll actually have the script for yarn test as well as App.test.tsx for running unit tests against React code (i.e. capable of running against tsx/jsx files etc.).

Jest is used for unit testing by default, but if you need to install Jest yourself simple run

yarn add --dev jest

The test script (within package.json) will execute react-scripts test but if we want to add our own script you could add

"jest": "jest --watch"

–watch will allow jest to monitor file changes and rerun tests automatically.

Create a folder off of your src folder (it can be at any depth) named __tests__ and within this we’ll add a simple .js file (or .ts) named files, for example number.test.js which we’ll create as a simple demonstration of writing tests and running the test runner. We should use either .test. or .spec. within the filename.

Within my number.test.js file I have the following

export function getNumber() {
    return 1234;
}

test('Test 1', () => {
    expect(getNumber()).toEqual(123);
});

test('Test 2', () => {
    expect(getNumber()).toEqual(1234);
});

Note: we can use “it” instead of “test” in the above

Obviously we’d normally not have the actually function we want to test within the test file, this is solely for simplicity of writing this post.

As you can see, each test comes with a string which is the name/description of the test, followed by a function which is executed by the test runner. Obviously in the above code “Test 1” will fail and “Test 2” will pass, so let’s run the test runner and see.

Like other test frameworks, we have functions to assert/expect certain values within our tests.

If you’ve added the script now run yarn jest or use yarn test. The Jest test runner will run and remain running, watching for file/test changes. Select the “a” option to run all tests after executing the jest script.

From the test runner (jest) you might wish to filter file name by regex, simply running tests against the __test__ folder.