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

This tutorial explains how to run Cypress tests, whether it’s a single test or multiple tests, with examples.

Cypress is a testing framework used to write unit tests in JavaScript applications.

Running All Test Files in JavaScript with Cypress

Cypress test files can be executed using either npm commands or the Cypress CLI.

  • Using npm command,

First, define scripts in package.json:

{
  "scripts": {
    "test": "cypress run --spec filepath"
    }
}

You can then execute all tests using either npm run test or npm test.

Cypress commands work after installing it either globally or locally in a project and configuring it in a project’s .ct file.

You can also use the Cypress CLI to execute tests. If Cypress is installed globally, use the following command

cypress run --spec src/

To run it locally:

./node_modules/.bin/cypress run --spec src/

How to Test a Single File Using Jest?

Sometimes, you might want to run a single test file using the Jest command.

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

The -- tells npm to pass the remaining arguments as a command-line argument to the npm test script.

Another method is using the Jest command line. If Jest is installed globally, use the following command:

jest src/components/button.spec.js

To run it locally

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

For example, if you have a calculator.spec.ts file containing the following:

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 shown below.

jest -i 'calculator`

Here, calculator matches the spec file name, i.e., calculator.spec.js.

You can also use the --testNamePatternor -t option to match with the test block.

Using npm scripts.

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

Then run the following command.

npm run test