w3resource

Configuring Jest


In this tutorial we will focus on configuring Jest. Jest's configuration can be defined inside the package.json file of your project, through jest.config.js file or using the --config <path/to/js|json> option. If you want to use your package.json to store Jest's config, the "jest" key has to be used on the top level so Jest knows how to find your settings:

{
  "name": "my-project",
  "jest": {
    "verbose": true
  }
}

Or by using JavaScript:

// jest.config.js
``module.exports = {
  verbose: true,
};

Always remember that the resulting configuration must be JSON-serializable.

When you are using the --config option, the JSON file should not contain a "jest" key:

{
  "bail": 1,
  "verbose": true
}

Options

These options enable you to control Jest's behavior in your package.json file. The Jest philosophy works great by default, but there are times when you just need more configuration power.

Defaults

Jest?s default options can be retrieved so that you can expand them if needed:

// jest.config.js

const {defaults} = require('jest-config');
module.exports = {
  //
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  // ...
};
  • automock [boolean]
  • bail [number | boolean]
  • browser [boolean]
  • cacheDirectory [string]
  • clearMocks [boolean]
  • collectCoverage [boolean]
  • collectCoverageFrom [array]
  • coverageDirectory [string]
  • coveragePathIgnorePatterns [array]
  • coverageReporters [array]
  • coverageThreshold [object]
  • dependencyExtractor [string]
  • displayName [string, object]
  • errorOnDeprecated [boolean]
  • extraGlobals [array]
  • forceCoverageMatch [array]
  • globals [object]
  • globalSetup [string]
  • globalTeardown [string]
  • maxConcurrency [number]
  • moduleDirectories [array]
  • moduleFileExtensions [array]
  • moduleNameMapper [object<string, string>]
  • modulePathIgnorePatterns [array]
  • modulePaths [array]
  • notify [boolean]
  • notifyMode [string]
  • preset [string]
  • prettierPath [string]
  • projects [array<string | ProjectConfig>]
  • reporters [array<moduleName | [moduleName, options]>]
  • resetMocks [boolean]
  • resetModules [boolean]
  • resolver [string]
  • restoreMocks [boolean]
  • rootDir [string]
  • roots [array]
  • runner [string]
  • setupFiles [array]
  • setupFilesAfterEnv [array]
  • snapshotResolver [string]
  • snapshotSerializers [array]
  • testEnvironment [string]
  • testEnvironmentOptions [Object]
  • testMatch [array]
  • testPathIgnorePatterns [array]
  • testRegex [string | array]
  • testResultsProcessor [string]
  • testRunner [string]
  • testSequencer [string]
  • testURL [string]
  • timers [string]
  • transform [object<string, pathToTransformer | [pathToTransformer, object]>]
  • transformIgnorePatterns [array]
  • unmockedModulePathPatterns [array]
  • verbose [boolean]
  • watchPathIgnorePatterns [array]
  • watchPlugins [array<string | [string, Object]>]
  • // [string]

Reference

automock [boolean]

Default: false

This option will tell Jest that all imported modules in your tests should be mocked automatically. All modules that are used in your tests will have a replacement implementation, keeping the API surface.

Example:

// utils.js
export default {
  authorize: () => {
    return 'token';
  },
  isAuthorized: secret => secret === 'wizard',
};```
//__tests__/automocking.test.js
```import utils from '../utils';

test('if utils mocked automatically', () => {
  // The Public methods of `utils` are now mock functions
  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized.mock).toBeTruthy();

  // You can either provide them with your own implementation
  // or you just pass the expected return value
  utils.authorize.mockReturnValue('mocked_token');
  utils.isAuthorized.mockReturnValue(true);

  expect(utils.authorize()).toBe('mocked_token');
  expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});

Note: Node modules will be automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js).

Note: Core modules, such as fs, will not be mocked by default. We can mock them explicitly, like jest.mock('fs').

bail [number | boolean]

Default: 0

By default, Jest will run all tests and will produce all errors into the console upon completion. The bail config option can then be used here to have Jest stop running tests after n failures. When we set bail to true, it is the same as setting bail to 1.

browser [boolean]

Default: false

Respect Browserify's "browser" field inside package.json if resolving modules. Some modules will export different versions based on whether they are operating in Node or a browser.

cacheDirectory [string]

Default: "/tmp/<path>"

The directory where Jest needs to store its cached dependency information.

Jest will attempt to scan your dependency tree once (up-front) and cache it so as to ease some of the filesystem raking that has to happen while running tests. This config option enables you customize where Jest stores that cache data on disk.

clearMocks [boolean]

Default: false

This will automatically clear mock calls and instances between every test. It is equivalent to calling jest.clearAllMocks() between each test. It does not remove any mock implementation that may have been provided.

collectCoverage [boolean]

Default: false

This will indicate whether the coverage information should be collected while executing the test. Because it retrofits all executed files with coverage collection statements, this mayslow down your test significantly slow.

collectCoverageFrom [array]

Default: undefined

This is an array of glob patterns that indicates a set of files for which coverage information should be collected. when a file matches the specified glob pattern, the coverage information will be collected for it even if no tests exist for this file and it is never required in the test suite.

Example:

{
  "collectCoverageFrom": [
    "**/*.{js,jsx}",
    "!**/node_modules/**",
    "!**/vendor/**"
  ]
}

This collects coverage information for all the files inside the project's rootDir, except the ones that match **/node_modules/** or **/vendor/**.

Note: This option will require collectCoverage to be set to true or Jest to be invoked with --coverage.

Help:

Whenever you are seeing coverage output like this:

======================== Coverage summary ===============================
Statements   : Unknown% ( 0/0 )
Branches     : Unknown% ( 0/0 )
Functions    : Unknown% ( 0/0 )
Lines        : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global not found.

It is most likely that your glob patterns are not matching any files.

coverageDirectory [string]

Default: undefined

This is the directory where Jest should output its coverage files.

coveragePathIgnorePatterns [array]

Default: ["/node_modules/"]

This is an array of regexp pattern strings that are matched against all file paths before executing the test. In the case where the file path matches any of the patterns, coverage information is skipped.

These pattern strings will match against the full path. You should use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that might have different root directories. For instance: ["<rootDir>/build/", "<rootDir>/node_modules/"].

coverageReporters [array]

Default: ["json", "lcov", "text", "clover"]

This is a list of reporter names that Jest uses when writing coverage reports. You can use any istanbul reporter.

Note: Setting this option will overwrite the default values. You should add "text" or "text-summary" to see a coverage summary in the console output.

coverageThreshold [object]

Default: undefined

This is used to configure minimum threshold enforcement for coverage results. You can specify thresholds as a glob, as a global, and as a file path or directory. In the case where the thresholds aren't met, jest fails. Thresholds that are specified as a positive number are taken to be the minimum percentage required. Thresholds that are specified as a negative number represent the maximum number of uncovered entities allowed.

For instance, given the following configuration jest fails when there is less than 80% branch, function, and line coverage, or when there are more than 10 uncovered statements:

{
  ...
  "jest": {
    "coverageThreshold": {
      "global": {
        "branches": 80,
        "functions": 80,
        "lines": 80,
        "statements": -10
      }
    }
  }
}

When globs or paths are specified alongside global, coverage data for matching paths is subtracted from overall coverage and thresholds are applied independently. Thresholds for globs will be applied to all files matching the glob. When the file specified by path is not found, error will be returned.

For instance, with the configuration below:

{
  ...
  "jest": {
    "coverageThreshold": {
      "global": {
        "branches": 50,
        "functions": 50,
        "lines": 50,
        "statements": 50
      },
      "./src/components/": {
        "branches": 40,
        "statements": 40
      },
      "./src/reducers/**/*.js": {
        "statements": 90
      },
      "./src/api/very-important-module.js": {
        "branches": 100,
        "functions": 100,
        "lines": 100,
        "statements": 100
      }
    }
  }
}

Jest will fail when:

  • The ./src/components directory has less than 40% statement or branch coverage.
  • One of the files that matches the ./src/reducers/**/*.js glob has less than 90% statement coverage.
  • The ./src/api/very-important-module.js file coverage is less than 100%.
  • Every remaining file combined has a coverage(global) that is less than 50%.

dependencyExtractor [string]

Default: undefined

This option will allow the use of a custom dependency extractor. It has to be a node module that exports an object with an extract function. E.g.:

const fs = require('fs');
const crypto = require('crypto');

module.exports = {
  extract(code, filePath, defaultExtract) {
    const deps = defaultExtract(code, filePath);
    // Will scan the file and add dependencies in `deps` (which is a `Set`)
    return deps;
  },
  getCacheKey() {
    return crypto
      .createHash('md5')
      .update(fs.readFileSync(__filename))
      .digest('hex');
  },
};

The extract function has to return an iterable (Array, Set, etc.) with the dependencies found in the code.

That module can also contain a getCacheKey function to generate a cache key that determines if the logic has changed and any cached artifacts that relies on it should be discarded.

displayName [string, object]

default: undefined

This will allow for a label to be printed alongside a test while it is running. This is more useful in multiproject repositories where there can be many jest configuration files. It visually tells the project that a test belongs to. Below are sample valid values.

module.exports = {
  displayName: 'CLIENT',
};

or

module.exports = {
  displayName: {
    name: 'CLIENT',
    color: 'blue',
  },
};

As a secondary option, an object with the properties color and name can be passed. This will allow for a custom configuration of the background color of the displayName. displayName will default to white when its value is a string. Jest will use chalk to provide the color. Thus, every of the valid options for colors that is supported by chalk will also be supported by jest.

errorOnDeprecated [boolean]

Default: false

This will make calling deprecated APIs throw helpful error messages. It is useful for easing the upgrade process.

extraGlobals [array]

Default: undefined

This will test files that are run inside a vm, which will slow calls to global context properties (e.g. Math). You can specify extra properties to be defined inside the vm for faster lookups with this option.

For instance, if your tests often call Math, pass it by setting extraGlobals.

{
  ...
  "jest": {
    "extraGlobals": ["Math"]
  }
}

forceCoverageMatch [array]

Default: ['']

Test files will normally be ignored from collecting code coverage. Using this option, you can overwrite the default behavior of tests and include files that are otherwise ignored in code coverage.

For instance, in the case where you have tests in source files named with .t.js extension as following:

// sum.t.js
export function sum(a, b) {
  return a + b;
}

if (process.env.NODE_ENV === 'test') {
  test('sum', () => {
    expect(sum(1, 2)).toBe(3);
  });
}

You can collect coverage from those files by setting forceCoverageMatch.

{
  ...
  "jest": {
    "forceCoverageMatch": ["**/*.t.js"]
  }
}

globals [object]

Default: {}

A set of global variables that has to be available in all test environments.

For instance, the following creates a global __DEV__ variable set to true in all test environments:

{
  ...
  "jest": {
    "globals": {
      "__DEV__": true
    }
  }
}

Note that, when you specify a global reference value (like an object or array) here, and some code mutates that value while running a test, that mutation is not persisted across test runs for other test files. Additionally, the globals object has to be json-serializable, so it cannot be used to specify global functions. For that you have to use setupFiles.

globalSetup [string]

Default: undefined

This option will allow the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function will get Jest's globalConfig object as a parameter.

Note: A global setup module that is configured in a project (using multi-project runner) will only be triggered only when you run at least one test from this project.

Note: Any global variables that are defined using globalSetup can only be read in globalTeardown. You cannot retrieve globals that are defined here in your test suites.

Note: While code transformation will be applied to the linked setup-file, Jest does not transform any code in node_modules. This is because of the need to load the actual transformers (e.g. babel or typescript) to perform transformation.

Example:

// setup.js
```module.exports = async () => {
  // ...
  //This will set reference to mongod in order to close the server during teardown.
  global.__MONGOD__ = mongod;
};```
// teardown.js
```module.exports = async function() {
  await global.__MONGOD__.stop();
};

globalTeardown [string]

Default: undefined

This option permits the use of a custom global teardown module which will export an async function that is triggered once after all test suites. This function will receive Jest's globalConfig object as a parameter.

Note: A global teardown module that is configured in a project (using multi-project runner) is triggered only when you run at least one test from this project.

Note: The same caveat concerning transformation of node_modules as for globalSetup will apply to globalTeardown.

maxConcurrency [number]

Default: 5

This is a number limiting the number of tests that are allowed to run at the same time when using test.concurrent. Any test that is above this limit will be queued and executed once a slot has been released.

moduleDirectories [array]

Default: ["node_modules"]

This is an array of directory names to be searched recursively up from the requiring module's location. When you set this option, you override the default, if you want to still search node_modules for packages include it along with any other options: ["node_modules", "bower_components"]

moduleFileExtensions [array]

Default: ["js", "json", "jsx", "ts", "tsx", "node"]

This is an array of file extensions your modules use. In the case where you require modules without specifying a file extension, these are the extensions Jest looks for, the order is from left-to-right.

It is recommended that you place the extensions that are most commonly used in your project on the left, that means if you are using TypeScript, you might consider moving "ts" and/or "tsx" to the beginning of our array.

moduleNameMapper [object<string, string>]

Default: null

This is a map from regular expressions to module names that allow you to stub out resources, such as images or styles with a single module.

Modules that are mapped to an alias are by default unmockedt, regardless of whether you enable automocking or not.

You should use <rootDir> string token to refer to rootDir value if you want to use file paths.

In addition, you can substitute captured regex groups with numbered backreferences.

Example:

{
  "moduleNameMapper": {
    "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
    "^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
    "module_name_(.*)": "<rootDir>/substituted_module_$1.js"
  }
}

The order that the mappings are defined matters. Patterns will be checked one by one until one fits. The most specific rule should be listed first.

Note: In the case where you provide module name without boundaries ^$ it can cause hard to spot errors. E.g. relay replaces all modules which contain relay as a substring in its name: relay, react-relay and graphql-relay are all pointed to your stub.

modulePathIgnorePatterns [array]

Default: []

This is an array of regexp pattern strings that are matched against all module paths before you consider those paths to be 'visible' to the module loader. In the case of a given module's path matching any of the patterns, it won?t be require()-able in the test environment.

These pattern strings will match against the full path. You should use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.

Example: ["<rootDir>/build/"].

modulePaths [array]

Default: []

This is an alternative API to setting the NODE_PATH env variable, the modulePaths is an array of absolute paths to the additional locations to search when resolving modules. You should use the <rootDir> string token to include the path to your project's root directory. Example: ["<rootDir>/app/"]

notify [boolean]

Default: false

This activates notifications for test results.

notifyMode [string]

Default: failure-change

This specifies notification mode. It requires notify: true.

Modes

  • always: will always send a notification.
  • failure: will send a notification when tests fail.
  • success: will send a notification when tests pass.
  • change: will send a notification when the status changed.
  • success-change: will send a notification when tests pass or once when it fails.
  • failure-change: will send a notification when tests fail or once when it passes.

preset [string]

Default: undefined

This is a preset that is used as a base for Jest's configuration. A preset has to point to an npm module that has a jest-preset.json or jest-preset.js file at the root.

For example, this preset foo-bar/jest-preset.js is configured as follows:

{
  "preset": "foo-bar"
}

Presets can also be relative filesystem paths.

 "preset": "./node_modules/foo-bar/jest-preset.js"
}

prettierPath [string]

Default: 'prettier'

This sets the path to the prettier node module used to update inline snapshots.

projects [array<string | ProjectConfig>]

Default: undefined

When you provide the projects configuration with an array of paths or glob patterns, Jest runs tests in all of the specified projects at the same time. This is good for monorepos or when you are working on multiple projects at the same time.

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

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

The projects feature can equally be used to run multiple configurations or multiple runners. You can pass an array of configuration objects, for this purpose. For instance, if you want 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, we recommend that you add a displayName for each project. This shows the displayName of a project next to its tests.

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

Default: undefined

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

Whenever custom reporters are specified, the default Jest reporters are overridden. If you want to keep default reporters, pass default as a module name.

This overrides default reporters:

{
  "reporters": ["<rootDir>/my-custom-reporter.js"]
}```
This uses custom reporter in addition to default reporters that Jest provides:
```{
  "reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}```
In addition, you can configure custom reporters by passing an options object as a second argument:
```{
  "reporters": [
    "default",
    ["<rootDir>/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}]
  ]
}

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

An example reporter:

// my-custom-reporter.js
```class 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;

Custom reporters can equally 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');
    }
  }
}

resetMocks [boolean]

Default: false

This will automatically reset mock state between every test. It is equivalent to calling jest.resetAllMocks() between each test. This leads to any mocks having their fake implementations removed but it does not restore their initial implementation.

resetModules [boolean]

Default: false

By default, each test file will get its own independent module registry. Enabling resetModules will go a step further and reset the module registry before running each individual test. This is useful in isolating modules for every test so that local module state doesn't conflict between tests. You can achieve this programmatically by using jest.resetModules().

resolver [string]

Default: undefined

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

{
  "basedir": string,
  "browser": bool,
  "defaultResolver": "function(request, options)",
  "extensions": [string],
  "moduleDirectory": [string],
  "paths": [string],
  "rootDir": [string]
}

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

Note: the defaultResolver passed as options will be the jest default resolver which might be useful when you write your custom one. It will take the same arguments as your custom one, e.g. (request, options).

restoreMocks [boolean]

Default: false

This will automatically restore mock state between every test. It is equivalent to calling jest.restoreAllMocks() between each test. This leads to any mocks having their fake implementations removed and then restores their initial implementation.

rootDir [string]

Default: Is the root of the directory containing your Jest config file or the package.json file or the pwd if it doesn?t find a package.json.

It is the root directory that Jest has to scan for tests and modules within. If you have your Jest config inside your package.json and you 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 will want to set this to 'src' or 'lib', corresponding to where the code is stored in your repository.

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

roots [array]

Default: ["<rootDir>"]

This is a list of paths to directories that Jest should use to search for files in.

Sometimes you only want Jest to search in a single sub-directory (like cases where you have a src/ directory in your repo), but prevent it from accessing the rest of the repository.

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

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

runner [string]

Default: "jest-runner"

This option will allow you to use a custom runner instead of Jest's default test runner. Some examples of runners include:

  • jest-runner-eslint
  • jest-runner-mocha
  • jest-runner-tsc
  • jest-runner-prettier

Note: The jest-runner- prefix of the package name can be omitted by the runner property.

If you want to write a test-runner, you should export a class which accepts globalConfig in the constructor, and that has a runTests method with the signature:

async runTests(
  tests: Array<Test>,
  watcher: TestWatcher,
  onStart: OnTestStart,
  onResult: OnTestSuccess,
  onFailure: OnTestFailure,
  options: TestRunnerOptions,
): Promise<void>

In the case where you need to restrict your test-runner to only run in serial rather then being executed in parallel, your class should have the property isSerial to be set to true.

setupFiles [array]

Default: []

This is a list of paths to modules that run some code to configure or to set up the testing environment. Each setupFile is run once per test file. Since all the tests run in their own environment, these scripts are executed in the testing environment immediately before executing the test code itself.

It is also worth noting that setupFiles executes before setupFilesAfterEnv.

setupFilesAfterEnv [array]

Default: []

This is a list of paths to modules that will run some code to configure or set up the testing framework before each test. Since setupFiles will execute before the test framework is installed in the environment, this script file will present you the opportunity of running some code immediately after the test framework has been installed in the environment.

In the case where you want a path to be relative to the root directory of your project, you need to include <rootDir> inside a path's string, such as "<rootDir>/a-configs-folder".

For instance, Jest will ship with several plug-ins to jasmine that work by monkey-patching the jasmine API. In the case where you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for instance), you might do so in these modules.

Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.

An example setupFilesAfterEnv array in a jest.config.js:

module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js'],
};```
An example jest.setup.js file
```jest.setTimeout(10000); // in milliseconds

snapshotResolver [string]

Default: undefined

This is the path to a module that can resolve test<->snapshot path. This config option enables you customize where Jest stores snapshot files on disk.

Below is an example snapshot resolver module:

module.exports = {
  // will resolve from test to snapshot path
  resolveSnapshotPath: (testPath, snapshotExtension) =>
    testPath.replace('__tests__', '__snapshots__') + snapshotExtension,

  // will resolve from snapshot to test path
  resolveTestPath: (snapshotFilePath, snapshotExtension) =>
    snapshotFilePath
      .replace('__snapshots__', '__tests__')
      .slice(0, -snapshotExtension.length),

  // this is an example test path, used for preflight consistency check of the implementation above
  testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};

snapshotSerializers [array]

Default: []

This is a list of paths to snapshot serializer modules Jest should use for snapshot testing.

Jest provides default serializers for built-in JavaScript types, HTML elements (since Jest 20.0.0+), ImmutableJS (since Jest 20.0.0+) and for React elements.

Below is an example serializer module:

// my-serializer-module
```module.exports = {
  print(val, serialize, indent) {
    return 'Pretty foo: ' + serialize(val.foo);
  },
  test(val) {
    return val && val.hasOwnProperty('foo');
  },
};

serialize is a function that will serialize a value using existing plugins.

If you want to use my-serializer-module as a serializer, the configuration would be as follows:

{
  ...
  "jest": {
    "snapshotSerializers": ["my-serializer-module"]
  }
}

Finally tests looks like this:

test(() => {
  const bar = {
    foo: {
      x: 1,
      y: 2,
    },
  };

  expect(bar).toMatchSnapshot();
});

Rendered snapshot:

Pretty foo: Object {
  "x": 1,
  "y": 2,
}

To make a dependency explicit instead of implicit, you can call expect.addSnapshotSerializer to add a module for an individual test file instead of adding its path to snapshotSerializers in Jest configuration.

testEnvironment [string]

Default: "jsdom"

The test environment that is used for testing. The default environment in Jest will be a browser-like environment through jsdom. In the case where you are building a node service, you will be able to use the node option to use a node-like environment instead.

By adding an @jest-environment docbock at the top of the file, you will be able specify another environment to be used for all tests in that file:

/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

You can create your own module that is used for setting up the test environment. The module has to export a class with setup, teardown and runScript methods. You can equally pass variables from this module to your test suites by assigning them to this.global object - this makes them available in your test suites as global variables.

The class may optionally expose a handleTestEvent method that binds to events fired by jest-circus.

Any docblock pragmas in test files that are passed to the environment constructor and can also be used for per-test configuration. In the case where the pragma does not have a value, it is present in the object with its value set to an empty string. When the pragma is not present, it will be absent in the object.

Note: TestEnvironment is sandboxed. Each test suite triggers setup/teardown in their own TestEnvironment.

Example:

// my-custom-environment
```const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.testPath = context.testPath;
    this.docblockPragmas = context.docblockPragmas;
  }

  async setup() {
    await super.setup();
    await someSetupTasks(this.testPath);
    this.global.someGlobalObject = createGlobalObject();

    // this will trigger if docblock contains @my-custom-pragma my-pragma-value
    if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
      // ...
    }
  }

  async teardown() {
    this.global.someGlobalObject = destroyGlobalObject();
    await someTeardownTasks();
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }

  handleTestEvent(event, state) {
    if (event.name === 'test_start') {
      // ...
    }
  }
}

module.exports = CustomEnvironment;```
// my-test-suite
```let someGlobalObject;

beforeAll(() => {
  someGlobalObject = global.someGlobalObject;
});

Note: by default, Jest comes with JSDOM@11. Jest is unable to upgrade for the time being due to JSDOM12 and the newer dropping support for Node 6. You can however install a custom testEnvironment with whichever version of JSDOM you want.

testEnvironmentOptions [Object]

Default: {}

Test environment options that is passed to the testEnvironment. The relevant options will depend on the environment. For instance, you can override options given to jsdom such as {userAgent: "Agent/007"}.

testMatch [array]

(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])

The glob patterns Jest will use to detect test files. By default it will look for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files that has a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It also finds files called test.js or spec.js.

testPathIgnorePatterns [array]

Default: ["/node_modules/"]

This is an array of regexp pattern strings that are matched against all test paths before executing the test. If your test path matches any of the patterns, it gets skipped.

These pattern strings will match against the full path. You should use the <rootDir> string token to include the path to your project's root directory so as to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/build/", "<rootDir>/node_modules/"].

testRegex [string | array]

Default: (/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$

This is the pattern or patterns that Jest uses to detect test files. By default it will look for .js, .jsx, .ts and .tsx files in __tests__ folders, as well as any files that has a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It also finds files called test.js or spec.js

Below is a visualization of the default regex:

+-- __tests__
?   +-- component.spec.js # test
?   +-- anything # test
+-- package.json # not test
+-- foo.test.js # test
+-- bar.spec.jsx # test
+-- component.js # not test

Note: testRegex tries to detect test files using the absolute file path therefore having a folder with name that match it runs all the files as tests

testResultsProcessor [string]

Default: undefined

This option will allow the use of a custom results processor. This processor has to be a node module that exports a function expecting an object with the following structure as the first argument and return it:

{
  "success": bool,
  "startTime": epoch,
  "numTotalTestSuites": number,
  "numPassedTestSuites": number,
  "numFailedTestSuites": number,
  "numRuntimeErrorTestSuites": number,
  "numTotalTests": number,
  "numPassedTests": number,
  "numFailedTests": number,
  "numPendingTests": number,
  "numTodoTests": number,
  "openHandles": Array<Error>,
  "testResults": [{
    "numFailingTests": number,
    "numPassingTests": number,
    "numPendingTests": number,
    "testResults": [{
      "title": string (message in it block),
      "status": "failed" | "pending" | "passed",
      "ancestorTitles": [string (message in describe blocks)],
      "failureMessages": [string],
      "numPassingAsserts": number,
      "location": {
        "column": number,
        "line": number
      }
    },
    ...
    ],
    "perfStats": {
      "start": epoch,
      "end": epoch
    },
    "testFilePath": absolute path to test file,
    "coverage": {}
  },
  ...
  ]
}

testRunner [string]

Default: jasmine2

This option enables the use of a custom test runner. jasmine2 is the default. You can custom test runner by specifying a path to a test runner implementation.

The test runner module has to export a function with the following signature:

function testRunner(
  config: Config,
  environment: Environment,
  runtime: Runtime,
  testPath: string,
): Promise<TestResult>;

testSequencer [string]

Default: @jest/test-sequencer

This option enables you to use a custom sequencer instead of Jest's default. sort return a Promise optionally.

Example:

Sorts test path alphabetically.

const Sequencer = require('@jest/test-sequencer').default;

class CustomSequencer extends Sequencer {
  sort(tests) {
    // The test structure information
    // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21
    const copyTests = Array.from(tests);
    return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1));
  }
}

module.exports = CustomSequencer;

testURL [string]

Default: http://localhost

This option will set the URL for the jsdom environment. This is reflected in properties such as location.href.

timers [string]

Default: real

We use fake timers when a piece of code sets a long timeout that we don't want to wait for in a test.

transform [object<string, pathToTransformer | [pathToTransformer, object]>]

Default: undefined

This is a map from regular expressions to paths to transformers. A transformer is a module that will provide a synchronous function for transforming source files. For instance, if you want to be able to use a new language feature in your modules or tests that is not supported by node yet, you could plug in one of many compilers that compile a future version of JavaScript to a current one.

Examples of such compilers are Babel, TypeScript and async-to-gen.

You can pass configuration to a transformer such as {filePattern: ['path-to-transformer', {options}]} For instance, if you want to configure babel-jest for non-default behavior, {"\\.js$": ['babel-jest', {rootMode: "upward"}]}

Note: a transformer will only run once per file unless the file has changed. During development of a transformer it might be useful to run Jest with --no-cache to frequently delete Jest's cache.

Note: when you are using the babel-jest transformer and you want to use an additional code preprocessor, you should keep in mind that when "transform" is overwritten in any way the babel-jest will not be loaded automatically anymore. If you want to use it to compile JavaScript code it must be explicitly defined.

transformIgnorePatterns [array]

Default: ["/node_modules/"]

This is an array of regexp pattern strings that are matched against all source file paths before transformation. When the test path matches any of the patterns, it won?t be transformed.

These pattern strings will match against the full path. You should use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.

Example: ["<rootDir>/bower_components/", "<rootDir>/node_modules/"].

unmockedModulePathPatterns [array]

Default: []

This is an array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns that is in this list, it will not be mocked automatically by the module loader.

This is useful for some commonly used 'utility' modules that are often used as implementation details almost all the time (like underscore/lo-dash, etc). It's generally the best practice to keep this list as small as possible and always use explicit jest.mock()/jest.unmock() calls inside individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test runs in.

You can override this setting in individual tests by explicitly calling jest.mock() at the top of the test file.

verbose [boolean]

Default: false

This indicates whether each individual test should be reported during the run. All errors are also shown on the bottom after execution.

watchPathIgnorePatterns [array]

Default: []

This is an array of RegExp patterns that are matched against all source file paths before re-running tests in watch mode. In the case where the file path matches any of the patterns, when it is updated, it won?t trigger a re-run of tests.

These patterns will match against the full path. You should use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: ["<rootDir>/node_modules/"]

watchPlugins [array<string | [string, Object]>]

Default: []

This option enables you to use a custom watch plugins.

Examples of watch plugins are:

  • jest-watch-master
  • jest-watch-select-projects
  • jest-watch-suspend
  • jest-watch-typeahead
  • jest-watch-yarn-workspaces

Note: The values in the watchPlugins property value are able to omit the jest-watch- prefix of the package name.

// [string]

No default

This option enable comments in package.json. you should include the comment text as the value of this key anywhere in package.json.

Example:

{
  "name": "my-project",
  "jest": {
    "//": "Comment goes here",
    "verbose": true
  }
}

Previous: Jest Object (API Reference)
Next: Jest CLI Options



Follow us on Facebook and Twitter for latest update.