- Configuring Jest·续1
- coverageProvider [string]
- coverageReporters [array<string | [string, options]>]
- coverageThreshold [object]
- dependencyExtractor [string]
- displayName [string, object]
- errorOnDeprecated [boolean]
- extensionsToTreatAsEsm [array<string>]
- extraGlobals [array<string>]
- forceCoverageMatch [array<string>]
- globals [object]
- globalSetup [string]
Configuring Jest·续1
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.
Note that using v8 is considered experimental. This uses V8’s builtin code coverage rather than one based on Babel. It is not as well tested, and it has also improved in the last few releases of Node. Using the latest versions of node (v14 at the time of this writing) will yield better results.
coverageReporters [array<string | [string, options]>]
Default: ["json", "lcov", "text", "clover"]
A list of reporter names that Jest uses when writing coverage reports. Any istanbul reporter can be used.
Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output.
Note: You can pass additional options to the istanbul reporter using the tuple form. 例如:
["json", ["lcov", {"projectRoot": "../../"}]]
For the additional information about the options object shape you can 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:
{ ... "jest": { "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": -10 } } }}
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:
{ ... "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 if:
-
The ./src/components directory has less than 40% branch or statement coverage.
-
One of the files matching the ./src/reducers/*/.js glob has less than 90% statement coverage.
-
The ./src/api/very-important-module.js file has less than 100% coverage.
-
Every remaining file combined has less than 50% coverage (global).
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. Here 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 name and color can be passed. This allows for a custom configuration of the background color of the displayName. displayName defaults to white when its value is a string. Jest uses chalk to provide the color. As such, all of the valid options for colors supported by chalk are also supported by jest.
errorOnDeprecated [boolean]
Default: 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.
Note: Jest’s ESM support is still experimental, see its docs for more details.
{ ... "jest": { "extensionsToTreatAsEsm": [".ts"] }}
extraGlobals [array<string>]
Default: undefined
Test files run inside a vm, which slows calls to global context properties (e.g. Math). With this option you can specify extra properties to be defined inside the vm for faster lookups.
For example, if your tests call Math often, you can pass it by setting extraGlobals.
{ ... "jest": { "extraGlobals": ["Math"] }}
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:
// sum.t.jsexport 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.
{ ... "jest": { "forceCoverageMatch": ["**/*.t.js"] }}
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:
{ ... "jest": { "globals": { "__DEV__": true } }}
Note that, 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 exports an async function that is triggered once before all test suites. This function gets Jest’s globalConfig object as a parameter.
Note: 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.
Note: Any global variables that are defined through globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.
