diff --git a/docs/CLI.md b/docs/CLI.md index bca78b1ca5b3..6b7de2f0b44e 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -180,8 +180,6 @@ Alias: `--collectCoverage`. Indicates that test coverage information should be c 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. - ### `--debug` Print debugging info about your Jest config. @@ -309,7 +307,13 @@ Allows the test suite to pass when no files are found. ### `--projects ... ` -Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the [`projects`](configuration#projects-arraystring--projectconfig) configuration option. Note that if configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. +Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the [`projects`](configuration#projects-arraystring--projectconfig) configuration option. + +:::note + +If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. + + ::: ### `--reporters` @@ -385,7 +389,9 @@ A JSON string with options that will be passed to the `testEnvironment`. The rel Adds a `location` field to test results. Useful if you want to report the location of a test in a reporter. -Note that `column` is 0-indexed while `line` is not. +:::note + +In the resulting object `column` is 0-indexed while `line` is not. ```json { @@ -394,6 +400,7 @@ Note that `column` is 0-indexed while `line` is not. } ``` +::: ### `--testMatch glob1 ... globN` The glob patterns Jest uses to detect test files. Please refer to the [`testMatch` configuration](Configuration.md#testmatch-arraystring) for details. @@ -454,8 +461,14 @@ Watch files for changes and rerun tests related to changed files. If you want to Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the `--watch` option. -Use `--watchAll=false` to explicitly disable the watch mode. Note that in most CI environments, this is automatically handled for you. +Use `--watchAll=false` to explicitly disable the watch mode. + +:::tip + +In most CI environments, this is automatically handled for you. + +::: ### `--watchman` -Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawling. Defaults to `true`. Disable using `--no-watchman`. +Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawling. Defaults to `true`. Disable using `--no-watchman`. diff --git a/docs/CodeTransformation.md b/docs/CodeTransformation.md index b7ceb9aaeb7a..2d16208eb10f 100644 --- a/docs/CodeTransformation.md +++ b/docs/CodeTransformation.md @@ -140,7 +140,11 @@ Though not required, we _highly recommend_ implementing `getCacheKey` as well, s Instead of having your custom transformer implement the `Transformer` interface directly, you can choose to export `createTransformer`, a factory function to dynamically create transformers. This is to allow having a transformer config in your jest config. -Note that [ECMAScript module](ECMAScriptModules.md) support is indicated by the passed in `supports*` options. Specifically `supportsDynamicImport: true` means the transformer can return `import()` expressions, which is supported by both ESM and CJS. If `supportsStaticESM: true` it means top level `import` statements are supported and the code will be interpreted as ESM and not CJS. See [Node's docs](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs) for details on the differences. +:::note + +[ECMAScript module](ECMAScriptModules.md) support is indicated by the passed in `supports*` options. Specifically `supportsDynamicImport: true` means the transformer can return `import()` expressions, which is supported by both ESM and CJS. If `supportsStaticESM: true` it means top level `import` statements are supported and the code will be interpreted as ESM and not CJS. See [Node's docs](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs) for details on the differences. + +::: :::tip diff --git a/docs/Configuration.md b/docs/Configuration.md index 1f3db639cda5..80d68060bcd2 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -275,9 +275,11 @@ These pattern strings match against the full path. Use the `` string to ### `coverageProvider` \[string] -Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. +Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. :::note -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. +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]>] @@ -764,7 +766,11 @@ const config: Config = { export default config; ``` -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`. +:::note + +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] @@ -1126,7 +1132,7 @@ export default config; :::info -Note that if you also have specified [`rootDir`](#rootdir-string) that the resolution of this file will be relative to that root directory. +If you also have specified [`rootDir`](#rootdir-string) that the resolution of this file will be relative to that root directory. ::: @@ -1754,10 +1760,14 @@ Pretty foo: Object { } ``` +:::note + To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) 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](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +::: + ### `testEnvironment` \[string] Default: `"node"` @@ -1865,7 +1875,11 @@ For example, in `jest-environment-jsdom`, you can override options given to [`js Both `jest-environment-jsdom` and `jest-environment-node` allow specifying `customExportConditions`, which allow you to control which versions of a library are loaded from `exports` in `package.json`. `jest-environment-jsdom` defaults to `['browser']`. `jest-environment-node` defaults to `['node', 'node-addons']`. -These options can also be passed in a docblock, similar to `testEnvironment`. Note that it must be parseable by `JSON.parse`. Example: +These options can also be passed in a docblock, similar to `testEnvironment`. + +:::note + +It must be parseable by `JSON.parse`. Example: ```js /** @@ -1878,6 +1892,8 @@ test('use jsdom and set the URL in this test file', () => { }); ``` +::: + ### `testFailureExitCode` \[number] Default: `1` @@ -2234,7 +2250,13 @@ It is possible to override this setting in individual tests by explicitly callin Default: `false` -Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. Note that if there is only one test file being run it will default to `true`. +Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. + +:::note + +If there is only one test file being run it will default to `true`. + +::: ### `watchPathIgnorePatterns` \[array<string>] diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 06105cd3c375..16dd9d80e76b 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -5,6 +5,9 @@ title: ECMAScript Modules :::caution +Due to its experimental nature there are many bugs and missing features in Jest's implementation, both known and unknown. You should check out the [tracking issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker for the latest status. + +Also note that the APIs Jest uses to implement ESM support is still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `14.13.1`). Jest ships with **experimental** support for ECMAScript Modules (ESM). The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. @@ -25,6 +28,7 @@ With the warnings out of the way, this is how you activate ESM support in your t 1. Beyond that, we attempt to follow `node`'s logic for activating "ESM mode" (such as looking at `type` in `package.json` or `.mjs` files), see [their docs](https://nodejs.org/api/esm.html#esm_enabling) for details. 1. If you want to treat other file extensions (such as `.jsx` or `.ts`) as ESM, please use the [`extensionsToTreatAsEsm` option](Configuration.md#extensionstotreatasesm-arraystring). +::: ## Differences between ESM and CommonJS Most of the differences are explained in [Node's documentation](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs), but in addition to the things mentioned there, Jest injects a special variable into all executed files - the [`jest` object](JestObjectAPI.md). To access this object in ESM, you need to import it from the `@jest/globals` module or use `import.meta`. @@ -41,6 +45,12 @@ import.meta.jest.useFakeTimers(); // jest === import.meta.jest => true ``` +:::note + + +We currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. + +::: ## Module mocking in ESM @@ -98,3 +108,4 @@ const exported = await import('./main.cjs'); // etc. ``` + diff --git a/docs/Es6ClassMocks.md b/docs/Es6ClassMocks.md index ad2fe2103018..f1773201ca2d 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -44,7 +44,11 @@ export default class SoundPlayerConsumer { Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with [mock functions](MockFunctions.md) that always return `undefined`. Method calls are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. -Please note that if you use arrow functions in your classes, they will _not_ be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function. +:::note + +If you use arrow functions in your classes, they will _not_ be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function. + +::: If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: @@ -240,9 +244,9 @@ jest.mock('./sound-player', () => { }); ``` -**_Note: Arrow functions won't work_** +:::note -Note that the mock can't be an arrow function because calling `new` on an arrow function is not allowed in JavaScript. So this won't work: +The mock can't be an arrow function because calling `new` on an arrow function is not allowed in JavaScript. So this won't work: ```javascript jest.mock('./sound-player', () => { @@ -255,6 +259,7 @@ jest.mock('./sound-player', () => { This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, unless the code is transpiled to ES5, e.g. by `@babel/preset-env`. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) +::: ## Mocking a specific method of a class Lets say that you want to mock or spy the method `playSoundFile` within the class `SoundPlayer`. A simple example: diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index f261e3c4bb0f..d8d07019174f 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -762,8 +762,9 @@ test('resolves to lemon', () => { return expect(Promise.resolve('lemon')).resolves.toBe('lemon'); }); ``` +:::note -Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. +Since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.resolves`: @@ -774,6 +775,7 @@ test('resolves to lemon', async () => { }); ``` +::: ### `.rejects` Use `.rejects` to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails. @@ -789,7 +791,9 @@ test('rejects to octopus', () => { }); ``` -Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. +:::note + +Since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.rejects`. @@ -799,6 +803,7 @@ test('rejects to octopus', async () => { }); ``` +::: ### `.toBe(value)` Use `.toBe` to compare primitive values or to check referential identity of object instances. It calls `Object.is` to compare values, which is even better for testing than `===` strict equality operator. diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 54496e0feda7..b40ad002da00 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -103,8 +103,9 @@ module.exports = api => { }; }; ``` +:::note -> Note: `babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: +`babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: ```javascript title="jest.config.js" module.exports = { @@ -112,8 +113,11 @@ module.exports = { }; ``` +::: + + ### Using webpack Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the [webpack guide](Webpack.md) to get started. @@ -162,6 +166,12 @@ npm install --save-dev ts-jest There are two ways to have [Jest global APIs](GlobalAPI.md) typed for test files written in TypeScript. +:::note + +For `@types/*` modules it's recommended to try to match the version of the associated module. For example, if you are using `26.4.0` of `jest` then using `26.4.x` of `@types/jest` is ideal. In general, try to match the major (`26`) and minor (`4`) version as closely as possible. + +::: + You can use type definitions which ships with Jest and will update each time you update Jest. Simply import the APIs from `@jest/globals` package: ```ts title="sum.test.ts" @@ -183,8 +193,13 @@ See the additional usage documentation of [`describe.each`/`test.each`](GlobalAP Or you may choose to install the [`@types/jest`](https://npmjs.com/package/@types/jest) package. It provides types for Jest globals without a need to import them. + ```bash npm2yarn npm install --save-dev @types/jest ``` -Note that `@types/jest` is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest), hence the latest Jest features or versions may not be covered yet. Try to match versions of Jest and `@types/jest` as closely as possible. For example, if you are using Jest `27.4.0` then installing `27.4.x` of `@types/jest` is ideal. +:::note + +`@types/jest` is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest), hence the latest Jest features or versions may not be covered yet. Try to match versions of Jest and `@types/jest` as closely as possible. For example, if you are using Jest `27.4.0` then installing `27.4.x` of `@types/jest` is ideal. + +::: \ No newline at end of file diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index 775d40d11d9c..2b48b0ee615c 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -23,6 +23,14 @@ import TOCInline from '@theme/TOCInline'; Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note + +The default timeout is 5 seconds. + +::: + Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. This is often useful if you want to clean up some global setup state that is shared across tests. @@ -63,6 +71,14 @@ If you want to run some cleanup after every test instead of after all tests, use Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note + +The default timeout is 5 seconds. + +::: + Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. This is often useful if you want to clean up some temporary state that is created by each test. @@ -103,6 +119,14 @@ If you want to run some cleanup just once, after all of the tests run, use `afte Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note + +The default timeout is 5 seconds. + +::: + Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. This is often useful if you want to set up some global state that will be used by many tests. @@ -139,6 +163,12 @@ If you want to run something before every test instead of before any test runs, Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +The default timeout is 5 seconds. + +::: + Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. This is often useful if you want to reset some global state that will be used by many tests. @@ -481,6 +511,12 @@ test('did not rain', () => { The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. +:::note + +If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. Jest will also wait if you **provide an argument to the test function**, usually called `done`. This could be handy when you want to test callbacks. See how to test async code [here](TestingAsyncCode.md#callbacks). + +For example, let's say `fetchBeverageList()` returns a promise that is supposed to resolve to a list that has `lemon` in it. You can test this with: + If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. For example, let's say `fetchBeverageList()` returns a promise that is supposed to resolve to a list that has `lemon` in it. You can test this with: ```js @@ -499,12 +535,24 @@ Jest will also wait if you **provide an argument to the test function**, usually ::: +::: + ### `test.concurrent(name, fn, timeout)` Also under the alias: `it.concurrent(name, fn, timeout)` :::caution +:::note + +`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues + +The first argument is the test name; the second argument is an asynchronous function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note + +The default timeout is 5 seconds. + `test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -523,12 +571,20 @@ test.concurrent('subtraction 2 numbers', async () => { }); ``` +::: + +:::note + +Use `maxConcurrency` in configuration to prevents Jest from executing more than the specified amount of tests at the same time + :::tip Use [`maxConcurrency`](Configuration.md/#maxconcurrency-number) configuration option to prevent Jest from executing more than the specified amount of tests at the same time. ::: +::: + ### `test.concurrent.each(table)(name, fn, timeout)` Also under the alias: `it.concurrent.each(table)(name, fn, timeout)` @@ -831,6 +887,14 @@ Also under the aliases: `it.only(name, fn, timeout)`, and `fit(name, fn, timeout When you are debugging a large test file, you will often only want to run a subset of tests. You can use `.only` to specify which tests are the only ones you want to run in that test file. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note + +The default timeout is 5 seconds. + +::: + Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. For example, let's say you had these tests: @@ -959,6 +1023,18 @@ Also under the alias: `it.todo(name)` Use `test.todo` when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo. +:::note + +If you supply a test callback function then the `test.todo` will throw an error. If you have already implemented the test and it is broken and you do not want it to run, then use `test.skip` instead. + +::: + +#### API + +- `name`: `String` the title of the test plan. + +Example: + ```js const add = (a, b) => a + b; diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 1272e37f497e..33fe7104336e 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -25,6 +25,10 @@ Disables automatic mocking in the module loader. :::info +See `automock` section of [configuration](Configuration.md#automock-boolean) for more information + +::: + Automatic mocking should be enabled via [`automock`](Configuration.md#automock-boolean) configuration option for this method to have any effect. Also see documentation of the configuration option for more details. ```js tab @@ -46,8 +50,6 @@ const config: Config = { export default config; ``` -::: - After `disableAutomock()` is called, all `require()`s will return the real versions of each module (rather than a mocked version). ```js title="utils.js" @@ -76,11 +78,9 @@ Examples of dependencies that might be considered "implementation details" are t Returns the `jest` object for chaining. -:::tip +:::note -When using `babel-jest`, calls to `disableAutomock()` will automatically be hoisted to the top of the code block. Use `autoMockOff()` if you want to explicitly avoid this behavior. - -::: +This method was previously called `autoMockOff`. When using `babel-jest`, calls to `disableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOff` if you want to explicitly avoid this behavior. ### `jest.enableAutomock()` @@ -88,7 +88,7 @@ Enables automatic mocking in the module loader. :::info -For more details on automatic mocking see documentation of [`automock`](Configuration.md#automock-boolean) configuration option. +See `automock` section of [configuration](Configuration.md#automock-boolean) for more information ::: @@ -115,14 +115,14 @@ test('original implementation', () => { }); ``` -Returns the `jest` object for chaining. - :::tip -When using `babel-jest`, calls to `enableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOn` if you want to explicitly avoid this behavior. +This method was previously called `autoMockOn`. When using `babel-jest`, calls to `enableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOn` if you want to explicitly avoid this behavior. ::: +Returns the `jest` object for chaining. + ### `jest.createMockFromModule(moduleName)` Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you. @@ -641,6 +641,8 @@ test('plays video', () => { }); ``` +::: + ### `jest.spyOn(object, methodName, accessType?)` Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively. @@ -699,22 +701,6 @@ test('plays audio', () => { }); ``` -### `jest.clearAllMocks()` - -Clears the `mock.calls`, `mock.instances`, `mock.contexts` and `mock.results` properties of all mocks. Equivalent to calling [`.mockClear()`](MockFunctionAPI.md#mockfnmockclear) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.resetAllMocks()` - -Resets the state of all mocks. Equivalent to calling [`.mockReset()`](MockFunctionAPI.md#mockfnmockreset) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.restoreAllMocks()` - -Restores all mocks back to their original value. Equivalent to calling [`.mockRestore()`](MockFunctionAPI.md#mockfnmockrestore) on every mocked function. Beware that `jest.restoreAllMocks()` only works when the mock was created with `jest.spyOn`; other mocks will require you to manually restore them. - ## Fake Timers ### `jest.useFakeTimers(fakeTimersConfig?)` @@ -910,6 +896,20 @@ This function is not available when using legacy fake timers implementation. ### `jest.setTimeout(timeout)` +Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. + +To set timeout intervals on different tests in the same file, use the [`timeout` option on each individual test](GlobalAPI.md#testname-fn-timeout). + +:::note + +The default timeout interval is 5 seconds if this method is not called. + +::: + +:::note + +If you want to set the timeout for all test files, a good place to do this is in `setupFilesAfterEnv`. + Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called. Example: @@ -949,3 +949,5 @@ test('will fail', () => { ``` Returns the `jest` object for chaining. + +::: diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index c0d7ea2243ee..adb5b4c62e2f 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -9,7 +9,11 @@ Manual mocks are used to stub out functionality with mock data. For example, ins Manual mocks are defined by writing a module in a `__mocks__/` subdirectory immediately adjacent to the module. For example, to mock a module called `user` in the `models` directory, create a file called `user.js` and put it in the `models/__mocks__` directory. Note that the `__mocks__` folder is case-sensitive, so naming the directory `__MOCKS__` will break on some systems. -> When we require that module in our tests (meaning we want to use the manual mock instead of the real implementation), explicitly calling `jest.mock('./moduleName')` is **required**. +:::note + +When we require that module in our tests (meaning we want to use the manual mock instead of the real implementation), explicitly calling `jest.mock('./moduleName')` is **required**. + +::: ## Mocking Node modules @@ -17,7 +21,11 @@ If the module you are mocking is a Node module (e.g.: `lodash`), the mock should Scoped modules (also known as [scoped packages](https://docs.npmjs.com/cli/v6/using-npm/scope)) can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called `@scope/project-name`, create a file at `__mocks__/@scope/project-name.js`, creating the `@scope/` directory accordingly. -> Warning: If we want to mock Node's core modules (e.g.: `fs` or `path`), then explicitly calling e.g. `jest.mock('path')` is **required**, because core Node modules are not mocked by default. +:::caution + +Warning: If we want to mock Node's core modules (e.g.: `fs` or `path`), then explicitly calling e.g. `jest.mock('path')` is **required**, because core Node modules are not mocked by default. + +::: ## Examples @@ -36,7 +44,11 @@ Scoped modules (also known as [scoped packages](https://docs.npmjs.com/cli/v6/us When a manual mock exists for a given module, Jest's module system will use that module when explicitly calling `jest.mock('moduleName')`. However, when `automock` is set to `true`, the manual mock implementation will be used instead of the automatically created mock, even if `jest.mock('moduleName')` is not called. To opt out of this behavior you will need to explicitly call `jest.unmock('moduleName')` in tests that should use the actual module implementation. -> Note: In order to mock properly, Jest needs `jest.mock('moduleName')` to be in the same scope as the `require/import` statement. +:::note + +In order to mock properly, Jest needs `jest.mock('moduleName')` to be in the same scope as the `require/import` statement. + +::: Here's a contrived example where we have a module that provides a summary of all the files in a given directory. In this case, we use the core (built in) `fs` module. @@ -92,7 +104,13 @@ fs.readdirSync = readdirSync; module.exports = fs; ``` -Now we write our test. Note that we need to explicitly tell that we want to mock the `fs` module because it’s a core Node module: +Now we write our test. + +:::note + +We need to explicitly tell that we want to mock the `fs` module because it’s a core Node module: + +::: ```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; diff --git a/docs/Puppeteer.md b/docs/Puppeteer.md index ff859e4c3522..b954c5be25cb 100644 --- a/docs/Puppeteer.md +++ b/docs/Puppeteer.md @@ -5,7 +5,11 @@ title: Using with puppeteer With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). -> Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +:::note + +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. + +::: ## Use jest-puppeteer Preset diff --git a/docs/SetupAndTeardown.md b/docs/SetupAndTeardown.md index d835a46c82e0..1c583dc9036b 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -97,7 +97,11 @@ describe('matching cities to foods', () => { }); ``` -Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. +:::note + +The top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. + +::: ```js beforeAll(() => console.log('1 - beforeAll')); @@ -169,7 +173,13 @@ describe('describe outer', () => { // test 3 ``` -Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other: +Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. + +:::note + +The `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other: + +::: ```js beforeEach(() => console.log('connection setup')); diff --git a/docs/TestingAsyncCode.md b/docs/TestingAsyncCode.md index ef8762eb7d87..53b141371c1e 100644 --- a/docs/TestingAsyncCode.md +++ b/docs/TestingAsyncCode.md @@ -115,7 +115,11 @@ If `done()` is never called, the test will fail (with timeout error), which is w If the `expect` statement fails, it throws an error and `done()` is not called. If we want to see in the test log why it failed, we have to wrap `expect` in a `try` block and pass the error in the `catch` block to `done`. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by `expect(data)`. -_Note: `done()` should not be mixed with Promises as this tends to lead to memory leaks in your tests._ +:::note + +`done()` should not be mixed with Promises as this tends to lead to memory leaks in your tests. + +::: ## `.resolves` / `.rejects` diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index f0ddf8406eb5..46041badb89c 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -7,7 +7,13 @@ Uh oh, something went wrong? Use this guide to resolve issues with Jest. ## Tests are Failing and You Don't Know Why -Try using the debugging support built into Node. Note: This will only work in Node.js 8+. +Try using the debugging support built into Node. + +:::note + +This will only work in Node.js 8+. + +::: Place a `debugger;` statement in any of your tests, and then, in your project's directory, run: @@ -17,13 +23,23 @@ or on Windows node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here] ``` -This will run Jest in a Node process that an external debugger can connect to. Note that the process will pause until the debugger has connected to it. +This will run Jest in a Node process that an external debugger can connect to. + +:::note + +Note that the process will pause until the debugger has connected to it. + +::: To debug in Google Chrome (or any Chromium-based browser), open your browser and go to `chrome://inspect` and click on "Open Dedicated DevTools for Node", which will give you a list of available node instances you can connect to. Click on the address displayed in the terminal (usually something like `localhost:9229`) after running the above command, and you will be able to debug Jest using Chrome's DevTools. The Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the `debugger` statement, execution will pause and you can examine the current scope and call stack. -> Note: the `--runInBand` cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time. +:::note + +Note: the `--runInBand` cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time. + +::: ## Debugging in VS Code @@ -175,7 +191,12 @@ jest --runInBand yarn test --runInBand ``` -Another alternative to expediting test execution time on Continuous Integration Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on Travis-CI, this can reduce test execution time in half. Note: The Travis CI _free_ plan available for open source projects only includes 2 CPU cores. +Another alternative to expediting test execution time on Continuous Integration Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on Travis-CI, this can reduce test execution time in half. + +:::note + +The Travis CI _free_ plan available for open source projects only includes 2 CPU cores. +::: ```bash # Using Jest CLI @@ -216,7 +237,11 @@ setTimeout(() => { When Jest runs your test to collect the `test`s it will not find any because we have set the definition to happen asynchronously on the next tick of the event loop. -_Note:_ This means when you are using `test.each` you cannot set the table asynchronously within a `beforeEach` / `beforeAll`. +:::note + +This means when you are using `test.each` you cannot set the table asynchronously within a `beforeEach` / `beforeAll`. + +::: ## Still unresolved? diff --git a/docs/TutorialReact.md b/docs/TutorialReact.md index 3f18ecbeab57..9e9b66b1e971 100644 --- a/docs/TutorialReact.md +++ b/docs/TutorialReact.md @@ -94,8 +94,12 @@ export default function Link({page, children}) { ); } ``` +:::note -> Note: Examples are using Function components, but Class components can be tested in the same way. See [React: Function and Class Components](https://reactjs.org/docs/components-and-props.html#function-and-class-components). **Reminders** that with Class components, we expect Jest to be used to test props and not methods directly. + +Examples are using Function components, but Class components can be tested in the same way. See [React: Function and Class Components](https://reactjs.org/docs/components-and-props.html#function-and-class-components). **Reminders** that with Class components, we expect Jest to be used to test props and not methods directly. + +::: Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file: diff --git a/docs/TutorialReactNative.md b/docs/TutorialReactNative.md index ddb60b230c31..7aac238e2e5a 100644 --- a/docs/TutorialReactNative.md +++ b/docs/TutorialReactNative.md @@ -21,11 +21,14 @@ Starting from react-native version 0.38, a Jest setup is included by default whe } } ``` +:::note -_Note: If you are upgrading your react-native application and previously used the `jest-react-native` preset, remove the dependency from your `package.json` file and change the preset to `react-native` instead._ +If you are upgrading your react-native application and previously used the `jest-react-native` preset, remove the dependency from your `package.json` file and change the preset to `react-native` instead. Run `yarn test` to run tests with Jest. +::: + ## Snapshot Test Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: diff --git a/docs/UsingMatchers.md b/docs/UsingMatchers.md index 11a01dcd189d..3be0ec296b94 100644 --- a/docs/UsingMatchers.md +++ b/docs/UsingMatchers.md @@ -155,7 +155,11 @@ test('compiling android goes as expected', () => { }); ``` -> Note: the function that throws an exception needs to be invoked within a wrapping function otherwise the `toThrow` assertion will fail. +:::note + +The function that throws an exception needs to be invoked within a wrapping function otherwise the `toThrow` assertion will fail. + +::: ## And More diff --git a/docs/WatchPlugins.md b/docs/WatchPlugins.md index a3064dd394ed..6092a5e2c3ff 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -130,8 +130,11 @@ Watch Usage › Press Enter to trigger a test run. ``` -**Note**: If the key for your plugin already exists as a default key, your plugin will override that key. +:::note +If the key for your plugin already exists as a default key, your plugin will override that key. + +::: ### `run(globalConfig, updateConfigAndRun)` To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. @@ -147,7 +150,11 @@ class MyWatchPlugin { } ``` -**Note**: If you do call `updateConfigAndRun`, your `run` method should not resolve to a truthy value, as that would trigger a double-run. +:::note + +If you do call `updateConfigAndRun`, your `run` method should not resolve to a truthy value, as that would trigger a double-run. + +::: #### Authorized configuration keys @@ -221,8 +228,16 @@ Any key not used by built-in functionality can be claimed, as you would expect. Should your plugin attempt to overwrite a reserved key, Jest will error out with a descriptive message, something like: -> Watch plugin YourFaultyPlugin attempted to register key `q`, that is reserved internally for quitting watch mode. Please change the configuration key for this plugin. +:::caution + +Watch plugin YourFaultyPlugin attempted to register key `q`, that is reserved internally for quitting watch mode. Please change the configuration key for this plugin. + +::: Third-party plugins are also forbidden to overwrite a key reserved already by another third-party plugin present earlier in the configured plugins list (`watchPlugins` array setting). When this happens, you’ll also get an error message that tries to help you fix that: -> Watch plugins YourFaultyPlugin and TheirFaultyPlugin both attempted to register key `x`. Please change the key configuration for one of the conflicting plugins to avoid overlap. +:::caution + +Watch plugins YourFaultyPlugin and TheirFaultyPlugin both attempted to register key `x`. Please change the key configuration for one of the conflicting plugins to avoid overlap. + +::: diff --git a/docs/Webpack.md b/docs/Webpack.md index 71f9cc607b8f..4e65cc52714e 100644 --- a/docs/Webpack.md +++ b/docs/Webpack.md @@ -143,7 +143,11 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t } ``` -> Note: `` is a special token that gets replaced by Jest with the root of your project. Most of the time this will be the folder where your `package.json` is located unless you specify a custom `rootDir` option in your configuration. +:::note + +`` is a special token that gets replaced by Jest with the root of your project. Most of the time this will be the folder where your `package.json` is located unless you specify a custom `rootDir` option in your configuration. + +::: Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH` env variable, which you can set, or make use of the `modulePaths` option. @@ -183,7 +187,11 @@ And finally, we have to handle the webpack `alias`. For that, we can make use of That's it! webpack is a complex and flexible tool, so you may have to make some adjustments to handle your specific application's needs. Luckily for most projects, Jest should be more than flexible enough to handle your webpack config. -> Note: For more complex webpack configurations, you may also want to investigate projects such as: [babel-plugin-webpack-loaders](https://github.com/istarkov/babel-plugin-webpack-loaders). +:::note + +For more complex webpack configurations, you may also want to investigate projects such as: [babel-plugin-webpack-loaders](https://github.com/istarkov/babel-plugin-webpack-loaders). + +::: ## Using with webpack 2 @@ -201,7 +209,9 @@ webpack 2 offers native support for ES modules. However, Jest runs in Node, and } ``` -> Note: Jest caches files to speed up test execution. If you updated .babelrc and Jest is still not working, try running Jest with `--no-cache`. +:::note + +Jest caches files to speed up test execution. If you updated .babelrc and Jest is still not working, try running Jest with `--no-cache`. If you use dynamic imports (`import('some-file.js').then(module => ...)`), you need to enable the `dynamic-import-node` plugin. @@ -219,4 +229,6 @@ If you use dynamic imports (`import('some-file.js').then(module => ...)`), you n } ``` +::: + For an example of how to use Jest with webpack with React, Redux, and Node, you can view one [here](https://github.com/jenniferabowd/jest_react_redux_node_webpack_complex_example).