From 2a380ba2a71f6046832bb0ed4f4b26fbad3364d6 Mon Sep 17 00:00:00 2001 From: Paul Reece Date: Fri, 17 Jun 2022 16:46:41 -0400 Subject: [PATCH 01/17] Added admonitions for all instances where necessary. --- docs/CLI.md | 22 ++++++++++-- docs/CodeTransformation.md | 4 +++ docs/Configuration.md | 23 ++++++++++-- docs/ECMAScriptModules.md | 14 ++++++-- docs/Es6ClassMocks.md | 7 +++- docs/ExpectAPI.md | 5 +++ docs/GettingStarted.md | 12 +++++-- docs/GlobalAPI.md | 70 +++++++++++++++++++++++++++++++------ docs/JestObjectAPI.md | 61 ++++++++++++++++++++++++++------ docs/ManualMocks.md | 26 +++++++++++--- docs/Puppeteer.md | 6 +++- docs/SetupAndTeardown.md | 12 ++++++- docs/SnapshotTesting.md | 6 +++- docs/TestingAsyncCode.md | 6 +++- docs/Troubleshooting.md | 35 ++++++++++++++++--- docs/TutorialReact.md | 6 +++- docs/TutorialReactNative.md | 5 ++- docs/UsingMatchers.md | 6 +++- docs/WatchPlugins.md | 22 +++++++++--- docs/Webpack.md | 18 ++++++++-- 20 files changed, 314 insertions(+), 52 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index b070f975a2dd..c88a93256b0b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -180,8 +180,11 @@ 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 + 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 +312,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 + + Note that if configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. + + ::: ### `--reporters` @@ -385,6 +394,8 @@ 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 + Note that `column` is 0-indexed while `line` is not. ```json @@ -394,6 +405,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,7 +466,13 @@ 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. + +:::note + +Note that in most CI environments, this is automatically handled for you. + +::: ### `--watchman` diff --git a/docs/CodeTransformation.md b/docs/CodeTransformation.md index b7ceb9aaeb7a..73d82f510058 100644 --- a/docs/CodeTransformation.md +++ b/docs/CodeTransformation.md @@ -140,8 +140,12 @@ 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 + 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. +::: + :::tip Make sure `process{Async}` method returns source map alongside with transformed code, so it is possible to report line information accurately in code coverage and test errors. Inline source maps also work but are slower. diff --git a/docs/Configuration.md b/docs/Configuration.md index ffc4b4f35b6a..df1e0f395929 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -276,9 +276,12 @@ 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`. +:::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. +::: + ### `coverageReporters` \[array<string | \[string, options]>] Default: `["clover", "json", "lcov", "text"]` @@ -763,9 +766,12 @@ const config: Config = { export default config; ``` +:::note 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` @@ -1747,11 +1753,13 @@ Pretty foo: Object { "y": 2, } ``` +:::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"` @@ -1859,7 +1867,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 + +Note that it must be parseable by `JSON.parse`. Example: ```js /** @@ -1872,6 +1884,8 @@ test('use jsdom and set the URL in this test file', () => { }); ``` +::: + ### `testFailureExitCode` \[number] Default: `1` @@ -2197,8 +2211,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 + +Note that if there is only one test file being run it will default to `true`. + +::: ### `watchPathIgnorePatterns` \[array<string>] Default: `[]` diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 199b7ff61b8c..46a82432bfe1 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -5,9 +5,15 @@ title: ECMAScript Modules Jest ships with _experimental_ support for ECMAScript Modules (ESM). -> Note that 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. +:::note -> 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`). +Note that 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. + +::: + +:::note + +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`). With the warnings out of the way, this is how you activate ESM support in your tests. @@ -21,6 +27,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`. @@ -37,5 +44,8 @@ import.meta.jest.useFakeTimers(); // jest === import.meta.jest => true ``` +:::note Please note that 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. + +::: \ No newline at end of file diff --git a/docs/Es6ClassMocks.md b/docs/Es6ClassMocks.md index ad2fe2103018..b18ce740e9fc 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -44,8 +44,12 @@ 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`. +:::note + 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. +::: + If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: ```javascript @@ -240,7 +244,7 @@ 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: @@ -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 aa25136d861b..85faaf18cb22 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -644,6 +644,7 @@ 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. @@ -656,6 +657,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. @@ -671,6 +673,8 @@ test('rejects to octopus', () => { }); ``` +:::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. Alternatively, you can use `async/await` in combination with `.rejects`. @@ -681,6 +685,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 870942cac091..bef11f6bc083 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. @@ -158,7 +162,11 @@ npm install --save-dev ts-jest You may also want to install the [`@types/jest`](https://www.npmjs.com/package/@types/jest) module for the version of Jest you're using. This will help provide full typing when writing your tests with TypeScript. -> 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. +:::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. + +::: ```bash npm2yarn npm install --save-dev @types/jest diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index ad68f1389c15..8853ab31d36d 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -19,7 +19,12 @@ 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. + +:::note +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. @@ -59,7 +64,13 @@ 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. + +:::note + +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. @@ -99,7 +110,13 @@ 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. + +:::note + +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. @@ -135,7 +152,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. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. + +:::note +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. @@ -477,7 +499,9 @@ 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. _Note: 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). +:::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: @@ -491,15 +515,27 @@ test('has lemon in it', () => { Even though the call to `test` will return right away, the test doesn't complete until the promise resolves as well. +::: + ### `test.concurrent(name, fn, timeout)` Also under the alias: `it.concurrent(name, fn, timeout)` Use `test.concurrent` if you want the test to run concurrently. -> 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 +:::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._ + +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('addition of 2 numbers', async () => { @@ -510,9 +546,13 @@ test.concurrent('subtraction 2 numbers', async () => { expect(5 - 3).toBe(2); }); ``` +::: + +:::note -> Note: Use `maxConcurrency` in configuration to prevents Jest from executing more than the specified amount of tests at the same time +Use `maxConcurrency` in configuration to prevents 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)` @@ -793,7 +833,13 @@ 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. + +:::note + +The default timeout is 5 seconds. + +::: For example, let's say you had these tests: @@ -921,7 +967,11 @@ 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. +:::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 diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 9d3629f2a7a5..cc6d3d80f26d 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -19,7 +19,11 @@ import TOCInline from '@theme/TOCInline'; Disables automatic mocking in the module loader. -> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information +:::info + +See `automock` section of [configuration](Configuration.md#automock-boolean) for more information + +::: After this method is called, all `require()`s will return the real versions of each module (rather than a mocked version). @@ -59,7 +63,11 @@ Examples of dependencies that might be considered "implementation details" are t Returns the `jest` object for chaining. -_Note: 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._ +:::note + +Note: 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()` @@ -67,7 +75,10 @@ Enables automatic mocking in the module loader. Returns the `jest` object for chaining. -> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information +:::info + +See `automock` section of [configuration](Configuration.md#automock-boolean) for more information + Example: @@ -92,7 +103,13 @@ test('original implementation', () => { }); ``` -_Note: 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._ +::: + +:::note + +Note: 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. + +::: ### `jest.createMockFromModule(moduleName)` @@ -276,12 +293,16 @@ jest.mock( ); ``` -> **Warning:** Importing a module in a setup file (as specified by `setupFilesAfterEnv`) will prevent mocking for the module in question, as well as all the modules that it imports. +:::danger + +Importing a module in a setup file (as specified by `setupFilesAfterEnv`) will prevent mocking for the module in question, as well as all the modules that it imports. Modules that are mocked with `jest.mock` are mocked only for the file that calls `jest.mock`. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module. Returns the `jest` object for chaining. +::: + ### `jest.unmock(moduleName)` Indicates that the module system should never return a mocked version of the specified module from `require()` (e.g. that it should always return the real module). @@ -376,7 +397,11 @@ In these rare scenarios you can use this API to manually fill the slot in the mo Returns the `jest` object for chaining. -_Note It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object._ +:::note + +It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object. + +::: ### `jest.requireActual(moduleName)` @@ -481,7 +506,9 @@ Determines if the given function is a mocked function. Creates a mock function similar to `jest.fn` but also tracks calls to `object[methodName]`. Returns a Jest [mock function](MockFunctionAPI.md). -_Note: By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation);`_ +:::note + +By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation);` Example: @@ -511,6 +538,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. @@ -588,7 +617,9 @@ Restores all mocks back to their original value. Equivalent to calling [`.mockRe The `mocked` test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source. It makes use of the latest TypeScript feature, so you even have argument types completion in the IDE (as opposed to `jest.MockInstance`). -_Note: while it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value._ +:::note + +While it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value. Example: @@ -628,6 +659,8 @@ test('direct', () => { }); ``` +::: + ## Fake Timers ### `jest.useFakeTimers(fakeTimersConfig?)` @@ -823,9 +856,15 @@ Set the default timeout interval (in milliseconds) for all tests and before/afte 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 -_Note: If you want to set the timeout for all test files, a good place to do this is in `setupFilesAfterEnv`._ +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`. Example: @@ -856,3 +895,5 @@ test('will fail', () => { ``` Returns the `jest` object for chaining. + +::: \ No newline at end of file diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index 178226d727f9..bfad24e23977 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 + +Note that 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..69edcc608f37 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -97,8 +97,12 @@ describe('matching cities to foods', () => { }); ``` +:::note + 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. +::: + ```js beforeAll(() => console.log('1 - beforeAll')); afterAll(() => console.log('1 - afterAll')); @@ -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 + +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: + +::: ```js beforeEach(() => console.log('connection setup')); diff --git a/docs/SnapshotTesting.md b/docs/SnapshotTesting.md index 08f81273a47e..f08ca8dfe117 100644 --- a/docs/SnapshotTesting.md +++ b/docs/SnapshotTesting.md @@ -40,10 +40,14 @@ exports[`renders correctly 1`] = ` The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. -> Note: The snapshot is directly scoped to the data you render – in our example the `` component with `page` prop passed to it. This implies that even if any other file has missing props (Say, `App.js`) in the `` component, it will still pass the test as the test doesn't know the usage of `` component and it's scoped only to the `Link.js`. Also, rendering the same component with different props in other snapshot tests will not affect the first one, as the tests don't know about each other. +:::note + +The snapshot is directly scoped to the data you render – in our example the `` component with `page` prop passed to it. This implies that even if any other file has missing props (Say, `App.js`) in the `` component, it will still pass the test as the test doesn't know the usage of `` component and it's scoped only to the `Link.js`. Also, rendering the same component with different props in other snapshot tests will not affect the first one, as the tests don't know about each other. More information on how snapshot testing works and why we built it can be found on the [release blog post](/blog/2016/07/27/jest-14). We recommend reading [this blog post](http://benmccormick.org/2016/09/19/testing-with-jest-snapshots-first-impressions/) to get a good sense of when you should use snapshot testing. We also recommend watching this [egghead video](https://egghead.io/lessons/javascript-use-jest-s-snapshot-testing-feature?pl=testing-javascript-with-jest-a36c4074) on Snapshot Testing with Jest. +::: + ### Updating Snapshots It's straightforward to spot when a snapshot test fails after a bug has been introduced. When that happens, go ahead and fix the issue and make sure your snapshot tests are passing again. Now, let's talk about the case when a snapshot test is failing due to an intentional implementation change. diff --git a/docs/TestingAsyncCode.md b/docs/TestingAsyncCode.md index ef8762eb7d87..7702b6826f50 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 + +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 5c9782875500..834032cf5770 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 @@ -172,7 +188,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 @@ -213,7 +234,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 eeebb2936956..d7092a158abf 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..a9bf450e7621 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 + +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 bcf2991083f1..0ba055838321 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -130,8 +130,10 @@ 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 +149,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 @@ -222,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 533e5b653ac1..82920c2343c4 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). From af23bdfec74e671f175f43807f7a5b31f859040d Mon Sep 17 00:00:00 2001 From: Paul Reece Date: Fri, 17 Jun 2022 16:51:34 -0400 Subject: [PATCH 02/17] Added admonitions for all instances where necessary. --- docs/Webpack.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/Webpack.md b/docs/Webpack.md index 82920c2343c4..72c8ebfe4bc8 100644 --- a/docs/Webpack.md +++ b/docs/Webpack.md @@ -228,7 +228,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). From 6f36c3acc6ec877d487ee912a87ac25c955ec62e Mon Sep 17 00:00:00 2001 From: PRVIQ Date: Sat, 20 Aug 2022 11:54:01 -0400 Subject: [PATCH 03/17] Test check --- docs/Webpack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/Webpack.md b/docs/Webpack.md index 72c8ebfe4bc8..596264ce5b67 100644 --- a/docs/Webpack.md +++ b/docs/Webpack.md @@ -230,4 +230,4 @@ 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). +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). \ No newline at end of file From a8675b32253f7df9a170e4076c18d680985eefcb Mon Sep 17 00:00:00 2001 From: PRVIQ Date: Mon, 22 Aug 2022 15:44:20 -0400 Subject: [PATCH 04/17] Prettier added. --- docs/CLI.md | 2 +- docs/WatchPlugins.md | 2 +- docs/Webpack.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index c88a93256b0b..0069d5cfff54 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -476,4 +476,4 @@ Note that 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/WatchPlugins.md b/docs/WatchPlugins.md index 0ba055838321..a5797432d1f3 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -238,6 +238,6 @@ Third-party plugins are also forbidden to overwrite a key reserved already by an :::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. +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 596264ce5b67..094ef346d921 100644 --- a/docs/Webpack.md +++ b/docs/Webpack.md @@ -230,4 +230,4 @@ 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). \ No newline at end of file +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). \ No newline at end of file From f58214c2b676fed1e1030cca80beadca5cff3922 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Mon, 19 Sep 2022 18:48:38 -0400 Subject: [PATCH 05/17] Update JestObjectAPI.md Removed duplicated messages --- docs/JestObjectAPI.md | 36 +++--------------------------------- 1 file changed, 3 insertions(+), 33 deletions(-) diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index cdea0de57fd5..249a0b383ecf 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -51,8 +51,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" @@ -85,12 +83,6 @@ Returns the `jest` object for chaining. Note: 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. -:::tip - -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()` Enables automatic mocking in the module loader. @@ -99,8 +91,6 @@ Enables automatic mocking in the module loader. See `automock` section of [configuration](Configuration.md#automock-boolean) for more information -For more details on automatic mocking see documentation of [`automock`](Configuration.md#automock-boolean) configuration option. - ::: Example: @@ -126,9 +116,6 @@ test('original implementation', () => { }); ``` - -::: - :::note Note: 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. @@ -137,13 +124,6 @@ Note: this method was previously called `autoMockOn`. When using `babel-jest`, c 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. - -::: - ### `jest.createMockFromModule(moduleName)` Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you. @@ -353,11 +333,6 @@ jest.mock( ); ``` - -:::danger - -Importing a module in a setup file (as specified by `setupFilesAfterEnv`) will prevent mocking for the module in question, as well as all the modules that it imports. - :::caution Importing a module in a setup file (as specified by [`setupFilesAfterEnv`](Configuration.md#setupfilesafterenv-array)) will prevent mocking for the module in question, as well as all the modules that it imports. @@ -369,10 +344,6 @@ Modules that are mocked with `jest.mock` are mocked only for the file that calls Returns the `jest` object for chaining. - -::: - - :::tip Writing tests in TypeScript? Use [`jest.Mocked`](MockFunctionAPI.md/#jestmockedsource) utility type or [`jest.mocked()`](MockFunctionAPI.md/#jestmockedsource-options) helper method to have your mocked modules typed. @@ -508,9 +479,6 @@ Returns the `jest` object for chaining. :::note -:::info - - It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object. ::: @@ -763,6 +731,8 @@ The `mocked` test helper provides typings on your mocked modules and even their While it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value. +::: + Example: ```ts @@ -1055,4 +1025,4 @@ test('will fail', () => { Returns the `jest` object for chaining. -::: \ No newline at end of file +::: From 617202a16a9a0750bba6b61ccb776271f0adbc79 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Mon, 19 Sep 2022 18:57:45 -0400 Subject: [PATCH 06/17] Update ECMAScriptModules.md --- docs/ECMAScriptModules.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 423fe7b6a3fd..297c09165402 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -5,9 +5,6 @@ title: ECMAScript Modules :::caution - -:::note - Note that 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. ::: From 55771df22c53ab943d264073fd23bdda925d8b51 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Tue, 20 Sep 2022 16:51:21 -0400 Subject: [PATCH 07/17] Update ECMAScriptModules.md --- docs/ECMAScriptModules.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 297c09165402..8b51c393068d 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -7,10 +7,6 @@ title: ECMAScript Modules Note that 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. -::: - -:::note - 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). From f6cc67d4e05fbe94d042a923fcd5e955adb11265 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Tue, 20 Sep 2022 16:53:32 -0400 Subject: [PATCH 08/17] Update JestObjectAPI.md --- docs/JestObjectAPI.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 249a0b383ecf..a4316dc010b2 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -477,7 +477,7 @@ In these rare scenarios you can use this API to manually fill the slot in the mo Returns the `jest` object for chaining. -:::note +:::info It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object. From abb67b504d393a7dcbb0361c67d6b1c28a006186 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Tue, 20 Sep 2022 16:55:50 -0400 Subject: [PATCH 09/17] Update JestObjectAPI.md --- docs/JestObjectAPI.md | 68 ------------------------------------------- 1 file changed, 68 deletions(-) diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index a4316dc010b2..0c89a8732893 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -706,74 +706,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. - - -### `jest.mocked(item: T, deep = false)` - -The `mocked` test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source. It makes use of the latest TypeScript feature, so you even have argument types completion in the IDE (as opposed to `jest.MockInstance`). - -:::note - -While it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value. - -::: - -Example: - -```ts -// foo.ts -export const foo = { - a: { - b: { - c: { - hello: (name: string) => `Hello, ${name}`, - }, - }, - }, - name: () => 'foo', -}; -``` - -```ts -// foo.spec.ts -import {foo} from './foo'; -jest.mock('./foo'); - -// here the whole foo var is mocked deeply -const mockedFoo = jest.mocked(foo, true); - -test('deep', () => { - // there will be no TS error here, and you'll have completion in modern IDEs - mockedFoo.a.b.c.hello('me'); - // same here - expect(mockedFoo.a.b.c.hello.mock.calls).toHaveLength(1); -}); - -test('direct', () => { - foo.name(); - // here only foo.name is mocked (or its methods if it's an object) - expect(jest.mocked(foo.name).mock.calls).toHaveLength(1); -}); -``` - -::: - - ## Fake Timers ### `jest.useFakeTimers(fakeTimersConfig?)` From 100dba1c787d74195078125e56b2f4939936055e Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Tue, 20 Sep 2022 16:56:40 -0400 Subject: [PATCH 10/17] Update JestObjectAPI.md --- docs/JestObjectAPI.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 0c89a8732893..bfcfb3698bf2 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -116,7 +116,7 @@ test('original implementation', () => { }); ``` -:::note +:::tip Note: 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. From 967e0dc261a2b0cb57b98aea6f89107007e80662 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 11:20:08 -0400 Subject: [PATCH 11/17] Update CLI.md --- docs/CLI.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index dd49bc16d1c0..b0139f30e96b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -182,7 +182,7 @@ Indicates which provider should be used to instrument code for coverage. Allowed :::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. ::: ### `--debug` @@ -316,7 +316,7 @@ Run tests from one or more projects, found in the specified paths; also takes pa :::note - Note that if configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. + If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. ::: @@ -396,7 +396,7 @@ Adds a `location` field to test results. Useful if you want to report the locati :::note -Note that `column` is 0-indexed while `line` is not. +`column` is 0-indexed while `line` is not. ```json { @@ -470,7 +470,7 @@ Use `--watchAll=false` to explicitly disable the watch mode. :::note -Note that in most CI environments, this is automatically handled for you. +In most CI environments, this is automatically handled for you. ::: From cd032548b1eaf986ba7859f1ea0ac29e45451196 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 11:21:00 -0400 Subject: [PATCH 12/17] Update CodeTransformation.md --- docs/CodeTransformation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CodeTransformation.md b/docs/CodeTransformation.md index 73d82f510058..2d16208eb10f 100644 --- a/docs/CodeTransformation.md +++ b/docs/CodeTransformation.md @@ -142,7 +142,7 @@ Instead of having your custom transformer implement the `Transformer` interface :::note -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. +[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. ::: From 2f7663082f507f74a7f12aa2c648094c4b7b1700 Mon Sep 17 00:00:00 2001 From: paulreece Date: Wed, 21 Sep 2022 11:30:37 -0400 Subject: [PATCH 13/17] Removed the word 'Note' from sentence beginnings. --- docs/Configuration.md | 21 ++++++++++++--------- docs/ECMAScriptModules.md | 4 ++-- docs/Es6ClassMocks.md | 4 ++-- docs/ExpectAPI.md | 4 ++-- docs/GettingStarted.md | 6 +++++- docs/GlobalAPI.md | 33 +++++++++------------------------ docs/JestObjectAPI.md | 11 ++--------- docs/ManualMocks.md | 4 ++-- docs/SetupAndTeardown.md | 6 +++--- docs/TestingAsyncCode.md | 2 +- docs/UsingMatchers.md | 2 +- docs/WatchPlugins.md | 1 + 12 files changed, 42 insertions(+), 56 deletions(-) diff --git a/docs/Configuration.md b/docs/Configuration.md index 8e194762368d..80d68060bcd2 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -275,10 +275,9 @@ 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`. -:::note +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. ::: @@ -766,9 +765,10 @@ const config: Config = { export default config; ``` + :::note -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`. +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`. ::: @@ -1132,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. ::: @@ -1759,6 +1759,7 @@ Pretty foo: Object { "y": 2, } ``` + :::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. @@ -1766,6 +1767,7 @@ To make a dependency explicit instead of implicit, you can call [`expect.addSnap 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"` @@ -1873,11 +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`. +These options can also be passed in a docblock, similar to `testEnvironment`. :::note -Note that it must be parseable by `JSON.parse`. Example: +It must be parseable by `JSON.parse`. Example: ```js /** @@ -2248,13 +2250,14 @@ 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. +Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. :::note -Note that if there is only one test file being run it will default to `true`. +If there is only one test file being run it will default to `true`. ::: + ### `watchPathIgnorePatterns` \[array<string>] Default: `[]` diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 8b51c393068d..16dd9d80e76b 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -5,7 +5,7 @@ title: ECMAScript Modules :::caution -Note that 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. +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). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); :::note -Please note that 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. +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. ::: diff --git a/docs/Es6ClassMocks.md b/docs/Es6ClassMocks.md index b18ce740e9fc..f1773201ca2d 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -46,7 +46,7 @@ Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can :::note -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. +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. ::: @@ -246,7 +246,7 @@ jest.mock('./sound-player', () => { :::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', () => { diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index 8fb25abe1f9e..d8d07019174f 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -764,7 +764,7 @@ test('resolves to 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`: @@ -793,7 +793,7 @@ test('rejects to octopus', () => { :::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 `.rejects`. diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 2115fa3abca7..b40ad002da00 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -198,4 +198,8 @@ Or you may choose to install the [`@types/jest`](https://npmjs.com/package/@type 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 727ab6efe8df..2b48b0ee615c 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -23,10 +23,10 @@ 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. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. :::note + The default timeout is 5 seconds. ::: @@ -71,7 +71,7 @@ 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. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. :::note @@ -81,7 +81,6 @@ 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. For example: @@ -120,8 +119,7 @@ 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. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. :::note @@ -131,7 +129,6 @@ 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. For example: @@ -166,8 +163,7 @@ 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. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. @@ -175,7 +171,6 @@ 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. For example: @@ -516,7 +511,6 @@ 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). @@ -525,7 +519,6 @@ For example, let's say `fetchBeverageList()` returns a promise that is supposed 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 test('has lemon in it', () => { return fetchBeverageList().then(list => { @@ -550,23 +543,18 @@ 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. +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. - ::: Use `test.concurrent` if you want the test to run concurrently. @@ -582,11 +570,11 @@ test.concurrent('subtraction 2 numbers', async () => { expect(5 - 3).toBe(2); }); ``` + ::: :::note - Use `maxConcurrency` in configuration to prevents Jest from executing more than the specified amount of tests at the same time :::tip @@ -595,8 +583,8 @@ Use [`maxConcurrency`](Configuration.md/#maxconcurrency-number) configuration op ::: - ::: + ### `test.concurrent.each(table)(name, fn, timeout)` Also under the alias: `it.concurrent.each(table)(name, fn, timeout)` @@ -899,8 +887,7 @@ 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. +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. :::note @@ -910,7 +897,6 @@ 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: ```js @@ -1037,7 +1023,6 @@ 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. diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index bfcfb3698bf2..33fe7104336e 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -25,7 +25,6 @@ Disables automatic mocking in the module loader. :::info - See `automock` section of [configuration](Configuration.md#automock-boolean) for more information ::: @@ -81,7 +80,7 @@ Returns the `jest` object for chaining. :::note -Note: 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. +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()` @@ -118,7 +117,7 @@ test('original implementation', () => { :::tip -Note: 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. +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. ::: @@ -339,7 +338,6 @@ Importing a module in a setup file (as specified by [`setupFilesAfterEnv`](Confi ::: - Modules that are mocked with `jest.mock` are mocked only for the file that calls `jest.mock`. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module. Returns the `jest` object for chaining. @@ -358,7 +356,6 @@ See [TypeScript Usage](MockFunctionAPI.md/#jestmockedsource) chapter of Mock Fun See [TypeScript Usage](MockFunctionAPI.md/#jestmockedsource-options) chapter of Mock Functions page for documentation. - ### `jest.unmock(moduleName)` Indicates that the module system should never return a mocked version of the specified module from `require()` (e.g. that it should always return the real module). @@ -476,7 +473,6 @@ In these rare scenarios you can use this API to manually fill the slot in the mo Returns the `jest` object for chaining. - :::info It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object. @@ -614,7 +610,6 @@ Since `jest.spyOn` is a mock. You could restore the initial state calling [jest. ::: - Example: ```js @@ -901,7 +896,6 @@ 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). @@ -918,7 +912,6 @@ If you want to set the timeout for all test files, a good place to do this is in 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: ```js diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index ef6ca932b32d..adb5b4c62e2f 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -104,11 +104,11 @@ fs.readdirSync = readdirSync; module.exports = fs; ``` -Now we write our test. +Now we write our test. :::note -Note that we need to explicitly tell that we want to mock the `fs` module because it’s a core Node module: +We need to explicitly tell that we want to mock the `fs` module because it’s a core Node module: ::: diff --git a/docs/SetupAndTeardown.md b/docs/SetupAndTeardown.md index 69edcc608f37..1c583dc9036b 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -99,7 +99,7 @@ describe('matching cities to foods', () => { :::note -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. +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. ::: @@ -173,11 +173,11 @@ describe('describe outer', () => { // test 3 ``` -Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. +Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. :::note -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: +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: ::: diff --git a/docs/TestingAsyncCode.md b/docs/TestingAsyncCode.md index 7702b6826f50..53b141371c1e 100644 --- a/docs/TestingAsyncCode.md +++ b/docs/TestingAsyncCode.md @@ -117,7 +117,7 @@ If the `expect` statement fails, it throws an error and `done()` is not called. :::note -Note: `done()` should not be mixed with Promises as this tends to lead to memory leaks in your tests. +`done()` should not be mixed with Promises as this tends to lead to memory leaks in your tests. ::: diff --git a/docs/UsingMatchers.md b/docs/UsingMatchers.md index a9bf450e7621..3be0ec296b94 100644 --- a/docs/UsingMatchers.md +++ b/docs/UsingMatchers.md @@ -157,7 +157,7 @@ test('compiling android goes as expected', () => { :::note -Note: the function that throws an exception needs to be invoked within a wrapping function otherwise the `toThrow` assertion will fail. +The function that throws an exception needs to be invoked within a wrapping function otherwise the `toThrow` assertion will fail. ::: diff --git a/docs/WatchPlugins.md b/docs/WatchPlugins.md index 8ea50f338f6c..6092a5e2c3ff 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -131,6 +131,7 @@ Watch Usage ``` :::note + If the key for your plugin already exists as a default key, your plugin will override that key. ::: From d1b55d44d149d10f815c65ecdd59bfade1852ac3 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 20:56:21 -0400 Subject: [PATCH 14/17] Update docs/CLI.md Co-authored-by: Tom Mrazauskas --- docs/CLI.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CLI.md b/docs/CLI.md index b0139f30e96b..6d414e5b6948 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -468,7 +468,7 @@ Watch files for changes and rerun all tests when something changes. If you want Use `--watchAll=false` to explicitly disable the watch mode. -:::note +:::tip In most CI environments, this is automatically handled for you. From 0807a44b9b028145412e7846b740d23e9fb0825c Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 20:56:28 -0400 Subject: [PATCH 15/17] Update docs/CLI.md Co-authored-by: Tom Mrazauskas --- docs/CLI.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CLI.md b/docs/CLI.md index 6d414e5b6948..4c35e3e1b386 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -316,7 +316,7 @@ Run tests from one or more projects, found in the specified paths; also takes pa :::note - If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. +If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. ::: From d9bb4e66257e7a51bc94709120d92d2b3884d111 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 20:56:45 -0400 Subject: [PATCH 16/17] Update docs/CLI.md Co-authored-by: Tom Mrazauskas --- docs/CLI.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CLI.md b/docs/CLI.md index 4c35e3e1b386..b032c1061359 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -396,7 +396,7 @@ Adds a `location` field to test results. Useful if you want to report the locati :::note -`column` is 0-indexed while `line` is not. +In the resulting object `column` is 0-indexed while `line` is not. ```json { From 26aa19d51ca27eae63881c2c6ac464cd36a36fd6 Mon Sep 17 00:00:00 2001 From: paulreece <96156234+paulreece@users.noreply.github.com> Date: Wed, 21 Sep 2022 20:58:02 -0400 Subject: [PATCH 17/17] Update CLI.md --- docs/CLI.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index b032c1061359..6b7de2f0b44e 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -180,11 +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 - -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.