Skip to content

Commit

Permalink
Merge branch 'main' into feat/programmatic-api
Browse files Browse the repository at this point in the history
  • Loading branch information
nicojs authored May 2, 2023
2 parents ac2b879 + d85d542 commit e5c254f
Show file tree
Hide file tree
Showing 36 changed files with 318 additions and 760 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

- `[docs]` Updated documentation for the `--runTestsByPath` CLI command ([#14004](https://github.com/facebook/jest/pull/14004))
- `[docs]` Updated documentation regarding the synchronous fallback when asynchronous code transforms are unavailable ([#14056](https://github.com/facebook/jest/pull/14056))
- `[docs]` Update jest statistics of use and downloads in website Index.
- `[docs]` Update jest statistics of use and downloads in website Index.

### Performance

Expand Down
2 changes: 1 addition & 1 deletion docs/SnapshotTesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Once you're finished, Jest will give you a summary before returning back to watc

Inline snapshots behave identically to external snapshots (`.snap` files), except the snapshot values are written automatically back into the source code. This means you can get the benefits of automatically generated snapshots without having to switch to an external file to make sure the correct value was written.

**Example:**
Example:

First, you write a test, calling `.toMatchInlineSnapshot()` with no arguments:

Expand Down
35 changes: 2 additions & 33 deletions docs/TutorialReact.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,9 @@ React 16 triggers these warnings due to how it checks element types, and the moc
### DOM Testing
If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/kentcdodds/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following two examples use react-testing-library and Enzyme.
If you'd like to assert, and manipulate your rendered components you can use [@testing-library/react](https://github.com/testing-library/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following example use `@testing-library/react`.

#### react-testing-library
#### @testing-library/react

```bash npm2yarn
npm install --save-dev @testing-library/react
Expand Down Expand Up @@ -261,37 +261,6 @@ it('CheckboxWithLabel changes the text after click', () => {
The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library).
#### Enzyme
```bash npm2yarn
npm install --save-dev enzyme
```
If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`.
Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](https://enzymejs.github.io/enzyme/docs/api/shallow.html) in this example.
```tsx title="__tests__/CheckboxWithLabel-test.js"
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CheckboxWithLabel from '../CheckboxWithLabel';
Enzyme.configure({adapter: new Adapter()});
it('CheckboxWithLabel changes the text after click', () => {
// Render a checkbox with label in the document
const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);
expect(checkbox.text()).toBe('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toBe('On');
});
```
The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/main/examples/enzyme).
### Custom transformers
If you need more advanced functionality, you can also build your own transformer. Instead of using `babel-jest`, here is an example of using `@babel/core`:
Expand Down
8 changes: 0 additions & 8 deletions examples/enzyme/.babelrc.js

This file was deleted.

28 changes: 0 additions & 28 deletions examples/enzyme/CheckboxWithLabel.js

This file was deleted.

18 changes: 0 additions & 18 deletions examples/enzyme/__tests__/CheckboxWithLabel-test.js

This file was deleted.

21 changes: 0 additions & 21 deletions examples/enzyme/package.json

This file was deleted.

71 changes: 46 additions & 25 deletions website/versioned_docs/version-25.x/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +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

Automatic mocking should be enabled via [`automock`](Configuration.md#automock-boolean) configuration option for this method to have any effect. Also see documentation of the configuration option for more details.

After this method is called, all `require()`s will return the real versions of each module (rather than a mocked version).
:::

Jest configuration:

Expand Down Expand Up @@ -55,19 +57,25 @@ test('original implementation', () => {

This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don't. For example, if you're writing a test for a module that uses a large number of dependencies that can be reasonably classified as "implementation details" of the module, then you likely do not want to mock them.

Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. Array.prototype methods) to highly common utility methods (e.g. underscore/lodash, array utilities, etc) and entire libraries like React.js.
Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. `Array.prototype` methods) to highly common utility methods (e.g. `underscore`, `lodash`, array utilities, etc) and entire libraries like `React.js`.

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.

Returns the `jest` object for chaining.
:::info

> 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:

Expand All @@ -92,7 +100,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._
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.genMockFromModule(moduleName)`

Expand All @@ -103,7 +117,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte
Example:

```js title="utils.js"
export default {
module.exports = {
authorize: () => {
return 'token';
},
Expand All @@ -112,11 +126,12 @@ export default {
```

```js title="__tests__/genMockFromModule.test.js"
const utils = jest.genMockFromModule('../utils').default;
const utils = jest.genMockFromModule('../utils');

utils.isAuthorized = jest.fn(secret => secret === 'not wizard');

test('implementation created by jest.genMockFromModule', () => {
expect(utils.authorize.mock).toBeTruthy();
expect(jest.isMockFunction(utils.authorize)).toBe(true);
expect(utils.isAuthorized('not wizard')).toBe(true);
});
```
Expand Down Expand Up @@ -176,7 +191,7 @@ module.exports = {
```

```js title="__tests__/example.test.js"
const example = jest.genMockFromModule('./example');
const example = jest.genMockFromModule('../example');

test('should run example code', () => {
// creates a new mocked function with no formal arguments.
Expand Down Expand Up @@ -272,7 +287,11 @@ 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.
:::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.

:::

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.

Expand Down Expand Up @@ -378,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._
:::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.

:::

### `jest.requireActual(moduleName)`

Expand Down Expand Up @@ -455,7 +478,7 @@ const otherCopyOfMyModule = require('myModule');

## Mock Functions

### `jest.fn(implementation)`
### `jest.fn(implementation?)`

Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a mock implementation.

Expand Down Expand Up @@ -628,10 +651,6 @@ Exhausts all tasks queued by `setImmediate()`.

### `jest.advanceTimersByTime(msToRun)`

##### renamed in Jest **22.0.0+**

Also under the alias: `.runTimersToTime()`

Executes only the macro task queue (i.e. all tasks queued by `setTimeout()` or `setInterval()` and `setImmediate()`).

When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via `setTimeout()` or `setInterval()`, and would be executed within this time frame will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within `msToRun` milliseconds.
Expand Down Expand Up @@ -688,16 +707,18 @@ This function is only available with the default [jest-circus](https://github.co

### `jest.setTimeout(timeout)`

Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called.

To set timeout intervals on different tests in the same file, use the [`timeout` option on each individual test](GlobalAPI.md#testname-fn-timeout).

_Note: The default timeout interval is 5 seconds if this method is not called._

_Note: If you want to set the timeout for all test files, a good place to do this is in `setupFilesAfterEnv`._
Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called.

Example:

```js
jest.setTimeout(1000); // 1 second
```

:::tip

To set timeout intervals on different tests in the same file, use the [`timeout` option on each individual test](GlobalAPI.md#testname-fn-timeout).

If you want to set the timeout for all test files, use [`testTimeout`](Configuration.md#testtimeout-number) configuration option.

:::
12 changes: 10 additions & 2 deletions website/versioned_docs/version-25.x/MockFunctionAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,11 @@ You can see an example of using Jest with TypeScript in our [GitHub repository](

### `jest.MockedFunction`

> `jest.MockedFunction` is available in the `@types/jest` module from version `24.9.0`.
:::tip

`jest.MockedFunction` is available in the `@types/jest` module from version `24.9.0`.

:::

The following examples will assume you have an understanding of how [Jest mock functions work with JavaScript](MockFunctions.md).

Expand Down Expand Up @@ -424,7 +428,11 @@ test('calculate calls add', () => {

### `jest.MockedClass`

> `jest.MockedClass` is available in the `@types/jest` module from version `24.9.0`.
:::tip

`jest.MockedClass` is available in the `@types/jest` module from version `24.9.0`.

:::

The following examples will assume you have an understanding of how [Jest mock classes work with JavaScript](Es6ClassMocks.md).

Expand Down
12 changes: 8 additions & 4 deletions website/versioned_docs/version-25.x/SnapshotTesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,15 @@ Once you're finished, Jest will give you a summary before returning back to watc

Inline snapshots behave identically to external snapshots (`.snap` files), except the snapshot values are written automatically back into the source code. This means you can get the benefits of automatically generated snapshots without having to switch to an external file to make sure the correct value was written.

> Inline snapshots are powered by [Prettier](https://prettier.io). To use inline snapshots you must have `prettier` installed in your project. Your Prettier configuration will be respected when writing to test files.
>
> If you have `prettier` installed in a location where Jest can't find it, you can tell Jest how to find it using the [`"prettierPath"`](./Configuration.md#prettierpath-string) configuration property.
:::info

Inline snapshots are powered by [Prettier](https://prettier.io). To use inline snapshots you must have `prettier` installed in your project. Your Prettier configuration will be respected when writing to test files.

If you have `prettier` installed in a location where Jest can't find it, you can tell Jest how to find it using the [`prettierPath`](./Configuration.md#prettierpath-string) configuration property.

:::

**Example:**
Example:

First, you write a test, calling `.toMatchInlineSnapshot()` with no arguments:

Expand Down
4 changes: 1 addition & 3 deletions website/versioned_docs/version-25.x/TutorialReact.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ React 16 triggers these warnings due to how it checks element types, and the moc
### DOM Testing
If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/kentcdodds/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following two examples use react-testing-library and Enzyme.
If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/testing-library/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following two examples use react-testing-library and Enzyme.

#### react-testing-library

Expand Down Expand Up @@ -276,8 +276,6 @@ test('CheckboxWithLabel changes the text after click', () => {
});
```
The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/main/examples/enzyme).
### Custom transformers
If you need more advanced functionality, you can also build your own transformer. Instead of using `babel-jest`, here is an example of using `@babel/core`:
Expand Down
Loading

0 comments on commit e5c254f

Please # to comment.