Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jest.run() or jest.runCLI() to run all tests or ways to run jest programmatically

Tags:

jestjs

How do I use jest.run() or jest.runCLI() to run all tests programmatically? What am I suppose to feed as an argument?

I tried to find documentation regarding them but fail.

And if the above functions don't work, what am I supposed to call if I want to run jest programmatically?

like image 756
lmc Avatar asked Jun 12 '18 23:06

lmc


People also ask

How does jest run tests in parallel?

To speed-up your tests, Jest can run them in parallel. By default, Jest will parallelise tests that are in different files. IMPORTANT: Paralellising tests mean using different threads to run test-cases simultaneously.


2 Answers

Jest is not supposed to be run programmatically. Maybe it will in the future.

Try to run following:

const jest = require("jest");

const options = {
  projects: [__dirname],
  silent: true,
};

jest
  .runCLI(options, options.projects)
  .then((success) => {
    console.log(success);
  })
  .catch((failure) => {
    console.error(failure);
  });

As success in then callback an object will be passed, containing globalConfig and results keys. Have a look on them, maybe it will help you.

like image 52
PeterDanis Avatar answered Sep 20 '22 00:09

PeterDanis


Here's example from my post on How to run Jest programmatically in node.js (Jest JavaScript API).

This time using TypeScript.

Install the dependencies

npm i -S jest-cli
npm i -D @types/jest-cli @types/jest

Make a call

import {runCLI} from 'jest-cli';
import ProjectConfig = jest.ProjectConfig;


const projectRootPath = '/path/to/project/root';

// Add any Jest configuration options here
const jestConfig: ProjectConfig = {
 roots: ['./dist/tests'],
 testRegex: '\\.spec\\.js$'
};

// Run the Jest asynchronously
const result = await runCLI(jestConfig as any, [projectRootPath]);

// Analyze the results
// (see typings for result format)
if (result.results.success) {
  console.log(`Tests completed`);
} else {
  console.error(`Tests failed`);
}

Also, regarding @PeterDanis answer, I'm not sure Jest will reject the promise in case of a failed tests. In my experience it will resovle with result.results.success === false.

like image 21
Slava Fomin II Avatar answered Sep 18 '22 00:09

Slava Fomin II