Introduction to Jest - coursehero/ch-react-workshop GitHub Wiki

The simplest example

A test is code that throws an error when the actual result of something does not match the expected output.

Here is an example of a pure function (functions which will always return the same output for a given input and not change the state of the world around them):

function sum(a, b) {
  return a + b;
}
module.exports = sum;
To test this function we would write a following small (or unit) test:
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

If you run npx jest you should see the following output:

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

Most tests are going to be more complicated than this, especially when rendering complex components and UI interactions with forms.

A common practice is to define a section in package.json such as this:

{
  "scripts": {
    "test": "jest"
  }
}

This allows you to use commands such as npm run test. See the scripts section in the official documentation for package.json.

Other related topics

Next steps

⚠️ **GitHub.com Fallback** ⚠️