What is Jest?

Jest’s slogan is a pleasant JavaScript test that, as the name suggests, is designed to test JavaScript code.

Jest has the following features:

  • High speed and sandbox. Jest runs parallel tests to maximize performance. Console messages are buffered and output test results. Sandbox test files and automatic global state are reset for each test, so there are no conflicts between test codes.

  • Built-in code coverage reports. Use –coverage to create code coverage reports. No additional libraries are required.

  • No configuration is required. Jest is already configured and ready to use when creating native projects using create-react-app or react-Native Init.

  • Has a powerful simulation library.

  • Use with Typescript

Start using Jest

Start by creating a new directory for BEGIN, then go to the folder and install the Jest dependencies.

npm install --save-dev jest
Copy the code

Once installed, a package.json configuration file is generated

Create a new sum.js file with the following code:

function sum(a, b) {
    return a + b;
}
module.exports = sum;
Copy the code

Create a new sum.spec.js or sum.test.js file with the following code:

const sum = require('./sum');

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

To make the command easier to understand and use, add the following configuration items to the package.json configuration file:

{
  "scripts": {
    "test": "jest"}}Copy the code

Finally, execute the following code:

npm run test
Copy the code

At this point, you have successfully completed your first Jest test.