How to run jest multiple or single file or test blocks with examples

This tutorial explains how to run jest tests with an example

Jest is a testing framework to write unit tests in javascript applications.

Running all test files in a javascript using jest framework

Jest test files can be executed using the npm command or jest cli command line execution. using npm command,

First, define commands in package.json

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

you can use the npm run test or npm test command to execute all tests.

For the jest command to work, install it globally or locally in a project and set up a jest in your project.

You can also use the jest cli command to execute.

If jest is installed globally, use the below command

jest src/

To run it locally

./node_modules/.bin/jest src/

How do I test a single file using Jest?

Sometimes we want to run a single test file using the jest command

npm test -- src/components/button.spec.js

If the test command is mapped to npm scripts in package.json -- tells to pass the remaining as a command line argument to the npm test script.

Another uses the jest command line. If jest is installed globally, use the below command

jest src/components/button.spec.js

To run it locally

./node_modules/.bin/jest src/components/button.spec.js

For example, the calculator.spec.ts file contains below

describe("calculator", () => {

it("add", () => {
expect(2+3).toBe(5);
});

it("substract", () => {
expect(20-6).toBe(14);
});

});

To run a single test file, use the -i option as given below

jest -i 'calculator`

calculator matched with spec file name ie calculator.spec.js

you can also use --testNamePattern or -toption that matched with test block

Using npm scripts:

{
"scripts": {
"test": "jest -i "calculator.spec.ts"
}
}

And run below command

npm run test