Configuring Jest·续3

When the projects configuration is provided with an array of paths or glob patterns, Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.

{  "projects": ["<​rootDir>", "<​rootDir>/examples/*"]}

This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance.

The projects feature can also be used to run multiple configurations or multiple runners. For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via jest-runner-eslint) in the same invocation of Jest:

{  "projects": [    {      "displayName": "test"    },    {      "displayName": "lint",      "runner": "jest-runner-eslint",      "testMatch": ["<​rootDir>/**/*.js"]    }  ]}

Note: When using multi-project runner, it’s recommended to add a displayName for each project. This will show the displayName of a project next to its tests.

reporters [array<​moduleName | [moduleName, options]>]

Default: undefined

Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements onRunStart, onTestStart, onTestResult, onRunComplete methods that will be called when any of those events occurs.

If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, default can be passed as a module name.

This will override default reporters:

{  "reporters": ["<​rootDir>/my-custom-reporter.js"]}

This will use custom reporter in addition to default reporters that Jest provides:

{  "reporters": ["default", "<​rootDir>/my-custom-reporter.js"]}

Additionally, custom reporters can be configured by passing an options object as a second argument:

{  "reporters": [    "default",    ["<​rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]  ]}

Custom reporter modules must define a class that takes a GlobalConfig and reporter options as constructor arguments:

Example reporter:

// my-custom-reporter.jsclass MyCustomReporter {  constructor(globalConfig, options) {    this._globalConfig = globalConfig;    this._options = options;  }  onRunComplete(contexts, results) {    console.log('Custom reporter output:');    console.log('GlobalConfig: ', this._globalConfig);    console.log('Options: ', this._options);  }}module.exports = MyCustomReporter;// or export default MyCustomReporter;

Custom reporters can also force Jest to exit with non-0 code by returning an Error from getLastError() methods

class MyCustomReporter {  // ...  getLastError() {    if (this._shouldFail) {      return new Error('my-custom-reporter.js reported an error');    }  }}

For the full list of methods and argument types see Reporter interface in packages/jest-reporters/src/types.ts

resetMocks [boolean]

Default: false

Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks() before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.

resetModules [boolean]

Default: false

By default, each test file gets its own independent module registry. Enabling resetModules goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that the local module state doesn’t conflict between tests. This can be done programmatically using jest.resetModules().

resolver [string]

Default: undefined

This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure as the second argument:

{  "basedir": string,  "defaultResolver": "function(request, options)",  "extensions": [string],  "moduleDirectory": [string],  "paths": [string],  "packageFilter": "function(pkg, pkgdir)",  "rootDir": [string]}

The function should either return a path to the module that should be resolved or throw an error if the module can’t be found.

Note: the defaultResolver passed as an option is the Jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. (request, options).

For example, if you want to respect Browserify’s "browser" field, you can use the following configuration:

{  ...  "jest": {    "resolver": "<​rootDir>/resolver.js"  }}
// resolver.jsconst browserResolve = require('browser-resolve');module.exports = browserResolve.sync;

By combining defaultResolver and packageFilter we can implement a package.json “pre-processor” that allows us to change how the default resolver will resolve modules. For example, imagine we want to use the field "module" if it is present, otherwise fallback to "main":

{  ...  "jest": {    "resolver": "my-module-resolve"  }}
// my-module-resolve packagemodule.exports = (request, options) => {  // Call the defaultResolver, so we leverage its cache, error handling, etc.  return options.defaultResolver(request, {    ...options,    // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb)    packageFilter: pkg => {      return {        ...pkg,        // Alter the value of `main` before resolving the package        main: pkg.module || pkg.main,      };    },  });};

restoreMocks [boolean]

Default: false

Automatically restore mock state before every test. Equivalent to calling jest.restoreAllMocks() before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation.

rootDir [string]

Default: The root of the directory containing your Jest config file or the package.json or the pwd if no package.json is found

The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your package.json and want the root directory to be the root of your repo, the value for this config param will default to the directory of the package.json.

Oftentimes, you’ll want to set this to 'src' or 'lib', corresponding to where in your repository the code is stored.

Note that using '<​rootDir>' as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your setupFiles config entry to point at the env-setup.js file at the root of your project, you could set its value to ["<​rootDir>/env-setup.js"].

roots [array<​string>]

Default: ["<​rootDir>"]

A list of paths to directories that Jest should use to search for files in.

There are times where you only want Jest to search in a single sub-directory (such as cases where you have a src/ directory in your repo), but prevent it from accessing the rest of the repo.

Note: While rootDir is mostly used as a token to be re-used in other configuration options, roots is used by the internals of Jest to locate test files and source files. This applies also when searching for manual mocks for modules from node_modules (mocks will need to live in one of the roots).

Note: By default, roots has a single entry <​rootDir> but there are cases where you may want to have multiple roots within one project, for example roots: ["<​rootDir>/src/", "<​rootDir>/tests/"].

runner [string]

Default: "jest-runner"

This option allows you to use a custom runner instead of Jest’s default test runner. Examples of runners include:

  • jest-runner-eslint

  • jest-runner-mocha

  • jest-runner-tsc

  • jest-runner-prettier

Note: The runner property value can omit the jest-runner- prefix of the package name.