Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Admonitions on website #12495 #12951

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 21 additions & 3 deletions docs/CLI.md
Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be already removed in the latest version of the docs and stay only in older ones.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed it.


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.
Expand Down Expand Up @@ -309,7 +312,13 @@ Allows the test suite to pass when no files are found.

### `--projects <path1> ... <pathN>`

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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can skip the "Note that" starts to all these sentences

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These have been removed from all .md files that have Note admonitions.


:::

### `--reporters`

Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -454,8 +466,14 @@ Watch files for changes and rerun tests related to changed files. If you want to

Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the `--watch` option.

Use `--watchAll=false` to explicitly disable the watch mode. Note that in most CI environments, this is automatically handled for you.
Use `--watchAll=false` to explicitly disable the watch mode.

:::note
paulreece marked this conversation as resolved.
Show resolved Hide resolved

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`.
4 changes: 4 additions & 0 deletions docs/CodeTransformation.md
Expand Up @@ -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.
Expand Down
23 changes: 21 additions & 2 deletions docs/Configuration.md
Expand Up @@ -276,9 +276,12 @@ These pattern strings match against the full path. Use the `<rootDir>` 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&lt;string | \[string, options]&gt;]

Default: `["clover", "json", "lcov", "text"]`
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -1753,11 +1759,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"`
Expand Down Expand Up @@ -1865,7 +1873,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
/**
Expand All @@ -1878,6 +1890,8 @@ test('use jsdom and set the URL in this test file', () => {
});
```

:::

### `testFailureExitCode` \[number]

Default: `1`
Expand Down Expand Up @@ -2234,8 +2248,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&lt;string&gt;]

Default: `[]`
Expand Down
15 changes: 15 additions & 0 deletions docs/ECMAScriptModules.md
Expand Up @@ -5,6 +5,13 @@ 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.

:::

:::note
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is already a caution block, why to split it?


Also note that the APIs Jest uses to implement ESM support is still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `14.13.1`).
Jest ships with **experimental** support for ECMAScript Modules (ESM).

The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker.
Expand All @@ -25,6 +32,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`.
Expand All @@ -41,6 +49,12 @@ 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.

:::

## Module mocking in ESM

Expand Down Expand Up @@ -98,3 +112,4 @@ const exported = await import('./main.cjs');

// etc.
```

7 changes: 6 additions & 1 deletion docs/Es6ClassMocks.md
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Expand All @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions docs/ExpectAPI.md
Expand Up @@ -762,6 +762,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.

Expand All @@ -774,6 +775,7 @@ test('resolves to lemon', async () => {
});
```

:::
### `.rejects`

Use `.rejects` to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.
Expand All @@ -789,6 +791,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`.
Expand All @@ -799,6 +803,7 @@ test('rejects to octopus', async () => {
});
```

:::
### `.toBe(value)`

Use `.toBe` to compare primitive values or to check referential identity of object instances. It calls `Object.is` to compare values, which is even better for testing than `===` strict equality operator.
Expand Down
13 changes: 12 additions & 1 deletion docs/GettingStarted.md
Expand Up @@ -103,17 +103,21 @@ 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 = {
transform: {},
};
```

:::

</details>


### 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.
Expand Down Expand Up @@ -162,6 +166,12 @@ npm install --save-dev ts-jest

There are two ways to have [Jest global APIs](GlobalAPI.md) typed for test files written in TypeScript.

:::note

For `@types/*` modules it's recommended to try to match the version of the associated module. For example, if you are using `26.4.0` of `jest` then using `26.4.x` of `@types/jest` is ideal. In general, try to match the major (`26`) and minor (`4`) version as closely as possible.

:::

You can use type definitions which ships with Jest and will update each time you update Jest. Simply import the APIs from `@jest/globals` package:

```ts title="sum.test.ts"
Expand All @@ -183,6 +193,7 @@ See the additional usage documentation of [`describe.each`/`test.each`](GlobalAP

Or you may choose to install the [`@types/jest`](https://npmjs.com/package/@types/jest) package. It provides types for Jest globals without a need to import them.


```bash npm2yarn
npm install --save-dev @types/jest
```
Expand Down