Jest 配置
Jest的理念在默认配置就能运行得很好,但有些时候我们还是需要发挥配置的功效。
为了方便对配置进行维护,建议在一个专用的Javascript、Typescript 或 JSON格式的配置文件中定义配置。 Jest会自动查找目录下文件名为 jest.config.js|ts|mjs|cjs|json
的配置文件, 您可以使用 --config
标记来指明配置文件的路径。
注意配置文件最后导出的对象一定要是可被JSON序列化的
配置文件应该只导出一个简单的对象,如下:
- JavaScript
- TypeScript
// 第一种方式
/** @type {import('jest').Config} */
const config = {
verbose: true,
};
module.exports = config;
// 第二种方式
import type {Config} from 'jest';
const config: Config = {
verbose: true,
};
export default config;
或者通过函数返回一个对象:
- JavaScript
- TypeScript
// 第一种方式
/** @returns {Promise<import('jest').Config>} */
module.exports = async () => {
return {
verbose: true,
};
};
// 第二种方式
import type {Config} from 'jest';
export default async (): Promise<Config> => {
return {
verbose: true,
};
};
提示:使用 Typescript 配置文件的还需给 Jest 安装 ts-node
, 请确保在项目中安装该依赖。
你也可以将配置作为一个普通对象保存在JSON格式的文件里:
{
"bail": 1,
"verbose": true
}
或者,可以在项目 package.json
里的 "jest"
键进行配置 Jest,如:
{
"name": "my-project",
"jest": {
"verbose": true
}
}
选项
你可以从 jest-config
获取 Jest 的默认配置,以便完成定制化配置:
- JavaScript
- TypeScript
const {defaults} = require('jest-config');
/** @type {import('jest').Config} */
const config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts', 'cts'],
};
module.exports = config;
import type {Config} from 'jest';
import {defaults} from 'jest-config';
const config: Config = {
moduleFileExtensions: [...defaults.moduleFileExtensions, 'mts'],
};
export default config;
automock
[boolean]bail
[number | boolean]cacheDirectory
[string]clearMocks
[boolean]collectCoverage
[boolean]collectCoverageFrom
[array]coverageDirectory
[string]coveragePathIgnorePatterns
[array<string>]coverageProvider
[string]coverageReporters
[array<string | [string, options]>]coverageThreshold
[object]dependencyExtractor
[string]displayName
[string, object]errorOnDeprecated
[boolean]extensionsToTreatAsEsm
[array<string>]fakeTimers
[object]forceCoverageMatch
[array<string>]globals
[object]globalSetup
[string]globalTeardown
[string]haste
[object]injectGlobals
[boolean]maxConcurrency
[number]maxWorkers
[number | string]moduleDirectories
[array<string>]moduleFileExtensions
[array<string>]moduleNameMapper
[object<string, string | array<string>>]modulePathIgnorePatterns
[array<string>]modulePaths
[array<string>]notify
[boolean]notifyMode
[string]openHandlesTimeout
[number]preset
[string]prettierPath
[string]projects
[array<string | ProjectConfig>]randomize
[boolean]reporters
[array<moduleName | [moduleName, options]>]resetMocks
[boolean]resetModules
[boolean]resolver
[string]restoreMocks
[boolean]rootDir
[string]roots
[array<string>]runner
[string]sandboxInjectedGlobals
[array<string>]setupFiles
[array]setupFilesAfterEnv
[array]showSeed
[boolean]slowTestThreshold
[number]snapshotFormat
[object]snapshotResolver
[string]snapshotSerializers
[array<string>]testEnvironment
[string]testEnvironmentOptions
[Object]testFailureExitCode
[number]testMatch
[array<string>]testPathIgnorePatterns
[array<string>]testRegex
[string | array<string>]testResultsProcessor
[string]testRunner
[string]testSequencer
[string]testTimeout
[number]transform
[object<string, pathToTransformer | [pathToTransformer, object]>]transformIgnorePatterns
[array<string>]unmockedModulePathPatterns
[array<string>]verbose
[boolean]watchPathIgnorePatterns
[array<string>]watchPlugins
[array<string | [string, Object]>]watchman
[boolean]workerIdleMemoryLimit
[number|string]//
[string]workerThreads
参考
automock
[boolean]
默认: false
此选项告诉Jest 您的测试中所有导入的模块都应该自动模拟。 在您测试中使用的所有模块都将有一个替换实现, 保留API表面。
示例:
export default {
authorize: () => 'token',
isAuthorized: secret => secret === 'wizard',
};
import utils from '../utils';
test('if utils mocked automatically', () => {
// Public methods of `utils` are now mock functions
expect(utils.authorize.mock).toBeTruthy();
expect(utils.isAuthorized.mock).toBeTruthy();
// You can provide them with your own implementation
// or 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();
});
Node modules are automatically mocked when you have a manual mock in place (e.g.: __mocks__/lodash.js
). More info here.
Node.js core modules, like fs
, are not mocked by default. 它们可以像 jest.mock('fs')
这样被明显的指定模拟。
bail
[number | boolean]
默认: 0
默认情况下,Jest运行所有测试,并在完成时将所有错误生成到控制台中。 此处可以使用bail config选项,使Jest在n
失败后停止运行测试。 将bail设置为 true
等于将bail设置为 1
。
cacheDirectory
[string]
默认: "/tmp/<path>"
Jest用来储存依赖信息缓存的目录。
Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem churn that needs to happen while running tests. 这一配置选项让你可以自定义Jest将缓存数据储存在磁盘的某个位置。
clearMocks
[boolean]
默认: false
在每次测试前自动清除mock调用、实例、上下文和结果。 在每次测试之前调用 jest.clearAllMocks()
这不会删除可能已提供的任何模拟实现。
collectCoverage
[boolean]
默认: false
指出是否收集测试时的覆盖率信息。 由于要带上覆盖率搜集语句重新访问所有执行过的文件,这可能会让你的测试执行速度被明显减慢。
Jest ships with two coverage providers: babel
(default) and v8
. See the coverageProvider
option for more details.
The babel
and v8
coverage providers use /* istanbul ignore next */
and /* c8 ignore next */
comments to exclude lines from coverage reports, respectively. For more information, you can view the istanbuljs
documentation and the c8
documentation.
collectCoverageFrom
[array]
Default: undefined
可以用一个 通配模式 的数组来指出仅哪些文件需要收集覆盖率信息。 如果一个文件匹配上指定的模式,即使没有关于它的测试用例存在,或也没有任何测试用例依赖它,它的覆盖率信息也将被收集。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/node_modules/**',
'!**/vendor/**',
],
};
export default config;
这个配置将收集项目的 rootDir
下的,除了能与 **/node_modules/**
或 **/vendor/**
匹配的所有文件的覆盖率信息。
Each glob pattern is applied in the order they are specified in the config. For example ["!**/__tests__/**", "**/*.js"]
will not exclude __tests__
because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after **/*.js
.
This option requires collectCoverage
to be set to true
or Jest to be invoked with --coverage
.
Help:
If you are seeing coverage output such as...
=============================== Coverage summary ===============================
Statements : Unknown% ( 0/0 )
Branches : Unknown% ( 0/0 )
Functions : Unknown% ( 0/0 )
Lines : Unknown% ( 0/0 )
================================================================================
Jest: Coverage data for global was not found.
Most likely your glob patterns are not matching any files. Refer to the micromatch documentation to ensure your globs are compatible.
coverageDirectory
[string]
Default: undefined
The directory where Jest should output its coverage files.
coveragePathIgnorePatterns
[array<string>]
Default: ["/node_modules/"]
An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped.
These pattern strings match against the full path. 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/", "<rootDir>/node_modules/"]
.
coverageProvider
[string]
Indicates which provider should be used to instrument code for coverage. Allowed values are babel
(default) or v8
.
coverageReporters
[array<string | [string, options]>]
Default: ["clover", "json", "lcov", "text"]
A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
Setting this option overwrites the default values. Add "text"
or "text-summary"
to see a coverage summary in the console output.
Additional options can be passed using the tuple form. For example, you may hide coverage report lines for all fully-covered files:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageReporters: ['clover', 'json', 'lcov', ['text', {skipFull: true}]],
};
export default config;
For more information about the options object shape refer to CoverageReporterWithOptions
type in the type definitions.
coverageThreshold
[object]
Default: undefined
This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as global
, as a glob, and as a directory or file path. If thresholds aren't met, jest will fail. Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed.
For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
};
export default config;
If globs or paths are specified alongside global
, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, an error is returned.
For example, with the following configuration:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
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,
},
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
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,
},
},
};
export default config;
Jest will fail if:
./src/components
目录的分支(branch)或语句(statement)覆盖率低于40%- 与
./src/reducers/**/*.js
匹配的任何一个文件的语句覆盖率低于90% - 文件
./src/api/very-important-module.js
的任意一种覆盖率低于 100% - 除了上述三种规则外的所有文件,任意一种覆盖率低于50%
dependencyExtractor
[string]
Default: undefined
This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an extract
function. E.g.:
const crypto = require('crypto');
const fs = require('fs');
module.exports = {
extract(code, filePath, defaultExtract) {
const deps = defaultExtract(code, filePath);
// 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 should 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 to determine if the logic has changed and any cached artifacts relying on it should be discarded.
displayName
[string, object]
default: undefined
Allows for a label to be printed alongside a test while it is running. This becomes more useful in multi-project repositories where there can be many jest configuration files. This visually tells which project a test belongs to.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: 'CLIENT',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: 'CLIENT',
};
export default config;
或者传入一个具有属性 name
和 color
的对象。 This allows for a custom configuration of the background color of the displayName. displayName
defaults to white when its value is a string. Jest 使用 chalk
来显示颜色。 因此,Jest 支持所有在 chalk
可用的选项。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
displayName: {
name: 'CLIENT',
color: 'blue',
},
};
export default config;
errorOnDeprecated
[boolean]
默认: false
Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process.
extensionsToTreatAsEsm
[array<string>]
Default: []
Jest will run .mjs
and .js
files with nearest package.json
's type
field set to module
as ECMAScript Modules. If you have any other files that should run with native ESM, you need to specify their file extension here.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
extensionsToTreatAsEsm: ['.ts'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
extensionsToTreatAsEsm: ['.ts'],
};
export default config;
Jest's ESM support is still experimental, see its docs for more details.
fakeTimers
[object]
Default: {}
The fake timers may be useful when a piece of code sets a long timeout that we don't want to wait for in a test. For additional details see Fake Timers guide and API documentation.
This option provides the default configuration of fake timers for all tests. Calling jest.useFakeTimers()
in a test file will use these options or will override them if a configuration object is passed. For example, you can tell Jest to keep the original implementation of process.nextTick()
and adjust the limit of recursive timers that will be run:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
doNotFake: ['nextTick'],
timerLimit: 1000,
},
};
export default config;
// install fake timers for this file using the options from Jest configuration
jest.useFakeTimers();
test('increase the limit of recursive timers for this and following tests', () => {
jest.useFakeTimers({timerLimit: 5000});
// ...
});
除了在每个文件里使用 jest.useFakeTimers()
之外,你还可以在全局 Jest 配置里启用 fake timers 选项:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
},
};
export default config;
配置选项
type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';
type ModernFakeTimersConfig = {
/**
* If set to `true` all timers will be advanced automatically by 20 milliseconds
* every 20 milliseconds. 设置数字可以提供一个自定义的时间间隔
* 默认为 false
*/
advanceTimers?: boolean | number;
/**
* 传入不该被替换的API列表 默认是 [] 代表全部的API都被会替换
*/
doNotFake?: Array<FakeableAPI>;
/** Whether fake timers should be enabled for all test files. The default is `false`. */
enableGlobally?: boolean;
/**
* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
* 默认为 false
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. 默认值是 `Date.now ()`。 */
now?: number;
/** Maximum number of recursive timers that will be run. The default is `100_000` timers. */
timerLimit?: number;
};
旧版本的假定时器
出于某些原因,你可能不得不使用旧版本的假定时器。 Here is how to enable it globally (additional options are not supported):
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
fakeTimers: {
enableGlobally: true,
legacyFakeTimers: true,
},
};
export default config;
:::
forceCoverageMatch
[array<string>]
Default: ['']
Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage.
For example, if you have tests in source files named with .t.js
extension as following:
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 with setting forceCoverageMatch
.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
forceCoverageMatch: ['**/*.t.js'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
forceCoverageMatch: ['**/*.t.js'],
};
export default config;
globals
[object]
Default: {}
A set of global variables that need to be available in all test environments.
For example, the following would create a global __DEV__
variable set to true
in all test environments:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
globals: {
__DEV__: true,
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
globals: {
__DEV__: true,
},
};
export default config;
If you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will not be persisted across test runs for other test files. In addition, the globals
object must be json-serializable, so it can't be used to specify global functions. For that, you should use setupFiles
.
globalSetup
[string]
Default: undefined
This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's globalConfig
and projectConfig
.
A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
Any global variables that are defined through globalSetup
can only be read in globalTeardown
. You cannot retrieve globals defined here in your test suites.
While code transformation is applied to the linked setup-file, Jest will not transform any code in node_modules
. This is due to the need to load the actual transformers (e.g. babel
or typescript
) to perform transformation.
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
// Set reference to mongod in order to close the server during teardown.
globalThis.__MONGOD__ = mongod;
};
module.exports = async function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPattern);
console.log(projectConfig.cache);
await globalThis.__MONGOD__.stop();
};
globalTeardown
[string]
Default: undefined
This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's globalConfig
and projectConfig
.
A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project.
The same caveat concerning transformation of node_modules
as for globalSetup
applies to globalTeardown
.
haste
[object]
Default: undefined
This will be used to configure the behavior of jest-haste-map
, Jest's internal file crawler/cache system. The following options are supported:
type HasteConfig = {
/** Whether to hash files using SHA-1. */
computeSha1?: boolean;
/** The platform to use as the default, e.g. 'ios'. */
defaultPlatform?: string | null;
/** Force use of Node's `fs` APIs rather than shelling out to `find` */
forceNodeFilesystemAPI?: boolean;
/**
* Whether to follow symlinks when crawling for files.
* This options cannot be used in projects which use watchman.
* Projects with `watchman` set to true will error if this option is set to true.
*/
enableSymlinks?: boolean;
/** Path to a custom implementation of Haste. */
hasteImplModulePath?: string;
/** All platforms to target, e.g ['ios', 'android']. */
platforms?: Array<string>;
/** Whether to throw on error on module collision. */
throwOnModuleCollision?: boolean;
/** Custom HasteMap module */
hasteMapModulePath?: string;
/** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */
retainAllFiles?: boolean;
};
injectGlobals
[boolean]
Default: true
Insert Jest's globals (expect
, test
, describe
, beforeEach
etc.) into the global environment. If you set this to false
, you should import from @jest/globals
, e.g.
import {expect, jest, test} from '@jest/globals';
jest.useFakeTimers();
test('some test', () => {
expect(Date.now()).toBe(0);
});
这个选项仅在使用jest-circus
进行测试时生效
maxConcurrency
[number]
Default: 5
A number limiting the number of tests that are allowed to run at the same time when using test.concurrent
. Any test above this limit will be queued and executed once a slot is released.
maxWorkers
[number | string]
设定运行测试的最大工作池数目。 In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases.
如果测试环境的CPU数量是不确定的,你可以使用百分比进行配置:
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
maxWorkers: '50%',
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
maxWorkers: '50%',
};
export default config;
moduleDirectories
[array<string>]
Default: ["node_modules"]
An array of directory names to be searched recursively up from the requiring module's location. 设置此选项将 * 覆盖 * 默认值。如果你想继续搜索 node_modules
中的模块,就把它和其他选项一起保留。例如:["node_modules"、"bower_components"]
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleDirectories: ['node_modules', 'bower_components'],
};
export default config;
It is discouraged to use '.'
as one of the moduleDirectories
, because this prevents scoped packages such as @emotion/react
from accessing packages with the same subdirectory name (react
). See this issue for more details. In most cases, it is preferable to use the moduleNameMapper configuration instead.
moduleFileExtensions
[array<string>]
Default: ["js", "mjs", "cjs", "jsx", "ts", "tsx", "json", "node"]
An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order.
We recommend placing the extensions most commonly used in your project on the left, so if you are using TypeScript, you may want to consider moving "ts" and/or "tsx" to the beginning of the array.
moduleNameMapper
[object<string, string | array<string>>]
Default: null
A map from regular expressions to module names or to arrays of module names that allow to stub out resources, like images or styles with a single module.
Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not.
Use <rootDir>
string token to refer to rootDir
value if you want to use file paths.
Additionally, you can substitute captured regex groups using numbered backreferences.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
moduleNameMapper: {
'^image![a-zA-Z0-9$_-]+$': 'GlobalImageStub',
'^[./a-zA-Z0-9$_-]+\\.png$': '<rootDir>/RelativeImageStub.js',
'module_name_(.*)': '<rootDir>/substituted_module_$1.js',
'assets/(.*)': [
'<rootDir>/images/$1',
'<rootDir>/photos/$1',
'<rootDir>/recipes/$1',
],
},
};
export default config;
The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. This is true for arrays of module names as well.
If you provide module names without boundaries ^$
it may cause hard to spot errors. E.g. relay
will replace all modules which contain relay
as a substring in its name: relay
, react-relay
and graphql-relay
will all be pointed to your stub.
modulePathIgnorePatterns
[array<string>]
Default: []
An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be require()
-able in the test environment.
These pattern strings match against the full path. 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.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
modulePathIgnorePatterns: ['<rootDir>/build/'],
};
export default config;