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", () => {

  it("substract", () => {


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
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.