Configuring Jest·续4
To write a test-runner, export a class with which accepts globalConfig in the constructor, and has a runTests method with the signature:
async runTests( tests: Array<Test>, watcher: TestWatcher, onStart: OnTestStart, onResult: OnTestSuccess, onFailure: OnTestFailure, options: TestRunnerOptions,): Promise<void>
If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property isSerial to be set as true.
setupFiles [array]
Default: []
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
It’s also worth noting that setupFiles will execute before setupFilesAfterEnv.
setupFilesAfterEnv [array]
Default: []
A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.
If you want a path to be relative to the root directory of your project, please include <rootDir> inside a path’s string, like "<rootDir>/a-configs-folder".
For example, Jest ships with several plug-ins to jasmine that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in these modules.
Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.
Example setupFilesAfterEnv array in a jest.config.js:
module.exports = { setupFilesAfterEnv: ['./jest.setup.js'],};
Example jest.setup.js file
jest.setTimeout(10000); // in milliseconds
slowTestThreshold [number]
Default: 5
The number of seconds after which a test is considered as slow and reported as such in the results.
snapshotResolver [string]
Default: undefined
The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk.
Example snapshot resolver module:
module.exports = { // resolves from test to snapshot path resolveSnapshotPath: (testPath, snapshotExtension) => testPath.replace('__tests__', '__snapshots__') + snapshotExtension, // resolves from snapshot to test path resolveTestPath: (snapshotFilePath, snapshotExtension) => snapshotFilePath .replace('__snapshots__', '__tests__') .slice(0, -snapshotExtension.length), // Example test path, used for preflight consistency check of the implementation above testPathForConsistencyCheck: 'some/__tests__/example.test.js',};
snapshotSerializers [array<string>]
Default: []
A list of paths to snapshot serializer modules Jest should use for snapshot testing.
Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See snapshot test tutorial for more information.
Example serializer module:
// my-serializer-modulemodule.exports = { serialize(val, config, indentation, depth, refs, printer) { return 'Pretty foo: ' + printer(val.foo); }, test(val) { return val && val.hasOwnProperty('foo'); },};
printer is a function that serializes a value using existing plugins.
To use my-serializer-module as a serializer, configuration would be as follows:
{ ... "jest": { "snapshotSerializers": ["my-serializer-module"] }}
Finally tests would look as follows:
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.
More about serializers API can be found here.
testEnvironment [string]
Default: "node"
The test environment that will be used for testing. The default environment in Jest is a Node.js environment. If you are building a web app, you can use a browser-like environment through jsdom instead.
By adding a @jest-environment docblock at the top of the file, you can 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 will be used for setting up the test environment. The module must export a class with setup, teardown and getVmContext methods. You can also pass variables from this module to your test suites by assigning them to this.global object – this will make them available in your test suites as global variables.
The class may optionally expose an asynchronous handleTestEvent method to bind to events fired by jest-circus. Normally, jest-circus test runner would pause until a promise returned from handleTestEvent gets fulfilled, except for the next events: start_describe_definition, finish_describe_definition, add_hook, add_test or error (for the up-to-date list you can look at SyncEvent type in the types definitions). That is caused by backward compatibility reasons and process.on('unhandledRejection', callback) signature, but that usually should not be a problem for most of the use cases.
Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object.
To use this class as your custom environment, refer to it by its full path within the project. For example, if your class is stored in my-custom-environment.js in some subfolder of your project, then the annotation might look like this:
/** * @jest-environment ./src/test/my-custom-environment */
Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.
Example:
// my-custom-environmentconst 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(); // 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(); } getVmContext() { return super.getVmContext(); } async handleTestEvent(event, state) { if (event.name === 'test_start') { // ... } }}module.exports = CustomEnvironment;
// my-test-suite/** * @jest-environment ./my-custom-environment */let someGlobalObject;beforeAll(() => { someGlobalObject = global.someGlobalObject;});
testEnvironmentOptions [Object]
Default: {}
Test environment options that will be passed to the testEnvironment. The relevant options depend on the environment. For example, you can override options given to jsdom such as {userAgent: "Agent/007"}.
testFailureExitCode [number]
Default: 1
The exit code Jest returns on test failure.
Note: This does not change the exit code in the case of Jest errors (e.g. invalid configuration).
