diff --git a/docs/BypassingModuleMocks.md b/docs/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/docs/BypassingModuleMocks.md +++ b/docs/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/docs/CodeTransformation.md b/docs/CodeTransformation.md index a7a71094f728..5cbc85a945d6 100644 --- a/docs/CodeTransformation.md +++ b/docs/CodeTransformation.md @@ -138,8 +138,7 @@ While `babel-jest` by default will transpile TypeScript files, Babel will not ve Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -149,9 +148,7 @@ module.exports = { }; ``` -```js -// jest.config.js - +```js title="jest.config.js" module.exports = { transform: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': diff --git a/docs/Configuration.md b/docs/Configuration.md index 56131b06edfb..52c2aefdbf42 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" // Sync object /** @type {import('@jest/types').Config.InitialOptions} */ const config = { @@ -36,8 +35,7 @@ module.exports = async () => { Or through TypeScript (if `ts-node` is installed): -```ts -// jest.config.ts +```ts title="jest.config.ts" import type {Config} from '@jest/types'; // Sync object @@ -73,8 +71,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -99,8 +96,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -404,9 +400,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -464,8 +458,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -473,8 +466,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -735,8 +727,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -816,8 +807,7 @@ For example, if you want to respect Browserify's [`"browser"` field](https://git } ``` -```js -// resolver.js +```js title="resolver.js" const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; @@ -1303,8 +1293,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/docs/Es6ClassMocks.md b/docs/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 485ef726092b..967ab4b06d3c 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 4f9c95cab35c..630e20b1dfc1 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -102,8 +98,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -112,8 +107,7 @@ export default { }; ``` -```js -// __tests__/createMockFromModule.test.js +```js title="__tests__/createMockFromModule.test.js" const utils = jest.createMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -147,8 +141,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -178,8 +171,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.createMockFromModule('./example'); test('should run example code', () => { @@ -220,11 +212,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/docs/JestPlatform.md b/docs/JestPlatform.md index 2273524221cd..7e638e040b63 100644 --- a/docs/JestPlatform.md +++ b/docs/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `JestWorker` that take ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index d481a5712e49..178226d727f9 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/docs/MockFunctionAPI.md b/docs/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/docs/MockFunctionAPI.md +++ b/docs/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/docs/MockFunctions.md b/docs/MockFunctions.md index d6dc73b999aa..2e686a92e837 100644 --- a/docs/MockFunctions.md +++ b/docs/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/docs/Puppeteer.md b/docs/Puppeteer.md index 53c16767b74e..16ab669a9ab2 100644 --- a/docs/Puppeteer.md +++ b/docs/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/docs/TimerMocks.md b/docs/TimerMocks.md index e97e2af97709..b053c1dbdfc9 100644 --- a/docs/TimerMocks.md +++ b/docs/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -82,8 +80,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -103,8 +100,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -140,8 +136,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/docs/TutorialAsync.md b/docs/TutorialAsync.md index f9418ad6651b..9c283074cabd 100644 --- a/docs/TutorialAsync.md +++ b/docs/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/docs/TutorialReact.md b/docs/TutorialReact.md index 7cce1e08cf10..5fcfa52a098b 100644 --- a/docs/TutorialReact.md +++ b/docs/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/docs/TutorialReactNative.md b/docs/TutorialReactNative.md index d89564980791..ddb60b230c31 100644 --- a/docs/TutorialReactNative.md +++ b/docs/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/docs/WatchPlugins.md b/docs/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/docs/Webpack.md b/docs/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/docs/Webpack.md +++ b/docs/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], diff --git a/website/src/css/docusaurusTheme.css b/website/src/css/docusaurusTheme.css index 0d7b8843d878..420a79605df1 100644 --- a/website/src/css/docusaurusTheme.css +++ b/website/src/css/docusaurusTheme.css @@ -70,3 +70,14 @@ html[data-theme='dark'] .footer--dark { .footer--dark .text--center { color: var(--grey); } + +.docusaurus-highlight-code-line { + background-color: rgba(0, 0, 0, 0.1); + display: block; + margin: 0 calc(-1 * var(--ifm-pre-padding)); + padding: 0 var(--ifm-pre-padding); +} + +html[data-theme='dark'] .docusaurus-highlight-code-line { + background-color: rgba(0, 0, 0, 0.3); +} diff --git a/website/versioned_docs/version-25.x/BypassingModuleMocks.md b/website/versioned_docs/version-25.x/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/website/versioned_docs/version-25.x/BypassingModuleMocks.md +++ b/website/versioned_docs/version-25.x/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/website/versioned_docs/version-25.x/Configuration.md b/website/versioned_docs/version-25.x/Configuration.md index 55ab8e845024..60c151c35305 100644 --- a/website/versioned_docs/version-25.x/Configuration.md +++ b/website/versioned_docs/version-25.x/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" /** @type {import('@jest/types').Config.InitialOptions} */ const config = { verbose: true, @@ -45,8 +44,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -71,8 +69,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -369,9 +366,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -429,8 +424,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -438,8 +432,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -672,8 +665,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -1147,8 +1139,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/website/versioned_docs/version-25.x/Es6ClassMocks.md b/website/versioned_docs/version-25.x/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/website/versioned_docs/version-25.x/Es6ClassMocks.md +++ b/website/versioned_docs/version-25.x/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/website/versioned_docs/version-25.x/GettingStarted.md b/website/versioned_docs/version-25.x/GettingStarted.md index 485ef726092b..423b1e4c42b6 100644 --- a/website/versioned_docs/version-25.x/GettingStarted.md +++ b/website/versioned_docs/version-25.x/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```js title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/website/versioned_docs/version-25.x/JestObjectAPI.md b/website/versioned_docs/version-25.x/JestObjectAPI.md index c13fa986bd6b..61c3885a65f5 100644 --- a/website/versioned_docs/version-25.x/JestObjectAPI.md +++ b/website/versioned_docs/version-25.x/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -98,8 +94,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -108,8 +103,7 @@ export default { }; ``` -```js -// __tests__/genMockFromModule.test.js +```js title="__tests__/genMockFromModule.test.js" const utils = jest.genMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -143,8 +137,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -174,8 +167,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.genMockFromModule('./example'); test('should run example code', () => { @@ -216,11 +208,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/website/versioned_docs/version-25.x/JestPlatform.md b/website/versioned_docs/version-25.x/JestPlatform.md index 568b39317aa5..1cc478cbacc7 100644 --- a/website/versioned_docs/version-25.x/JestPlatform.md +++ b/website/versioned_docs/version-25.x/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `Worker` that takes th ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/website/versioned_docs/version-25.x/ManualMocks.md b/website/versioned_docs/version-25.x/ManualMocks.md index 2f58f0606375..9387ca82fc5a 100644 --- a/website/versioned_docs/version-25.x/ManualMocks.md +++ b/website/versioned_docs/version-25.x/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/website/versioned_docs/version-25.x/MockFunctionAPI.md b/website/versioned_docs/version-25.x/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/website/versioned_docs/version-25.x/MockFunctionAPI.md +++ b/website/versioned_docs/version-25.x/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/website/versioned_docs/version-25.x/MockFunctions.md b/website/versioned_docs/version-25.x/MockFunctions.md index 873dfff9462a..d583d55bdca8 100644 --- a/website/versioned_docs/version-25.x/MockFunctions.md +++ b/website/versioned_docs/version-25.x/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/website/versioned_docs/version-25.x/Puppeteer.md b/website/versioned_docs/version-25.x/Puppeteer.md index c0b92dfd97dd..65c78ff9faab 100644 --- a/website/versioned_docs/version-25.x/Puppeteer.md +++ b/website/versioned_docs/version-25.x/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/website/versioned_docs/version-25.x/TimerMocks.md b/website/versioned_docs/version-25.x/TimerMocks.md index ff8a16ef988a..8086ccd10b8b 100644 --- a/website/versioned_docs/version-25.x/TimerMocks.md +++ b/website/versioned_docs/version-25.x/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -64,8 +62,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -85,8 +82,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -124,8 +120,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/website/versioned_docs/version-25.x/TutorialAsync.md b/website/versioned_docs/version-25.x/TutorialAsync.md index dd8a2da77977..0534aec12667 100644 --- a/website/versioned_docs/version-25.x/TutorialAsync.md +++ b/website/versioned_docs/version-25.x/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/website/versioned_docs/version-25.x/TutorialReact.md b/website/versioned_docs/version-25.x/TutorialReact.md index d6be521ae589..39d0eaa01018 100644 --- a/website/versioned_docs/version-25.x/TutorialReact.md +++ b/website/versioned_docs/version-25.x/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/website/versioned_docs/version-25.x/TutorialReactNative.md b/website/versioned_docs/version-25.x/TutorialReactNative.md index beabd0d09e2d..18b740a54290 100644 --- a/website/versioned_docs/version-25.x/TutorialReactNative.md +++ b/website/versioned_docs/version-25.x/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/website/versioned_docs/version-25.x/WatchPlugins.md b/website/versioned_docs/version-25.x/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/website/versioned_docs/version-25.x/WatchPlugins.md +++ b/website/versioned_docs/version-25.x/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/website/versioned_docs/version-25.x/Webpack.md b/website/versioned_docs/version-25.x/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/website/versioned_docs/version-25.x/Webpack.md +++ b/website/versioned_docs/version-25.x/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], diff --git a/website/versioned_docs/version-26.x/BypassingModuleMocks.md b/website/versioned_docs/version-26.x/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/website/versioned_docs/version-26.x/BypassingModuleMocks.md +++ b/website/versioned_docs/version-26.x/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/website/versioned_docs/version-26.x/Configuration.md b/website/versioned_docs/version-26.x/Configuration.md index fdf5b8aaf8c9..2e4dcab9b114 100644 --- a/website/versioned_docs/version-26.x/Configuration.md +++ b/website/versioned_docs/version-26.x/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" // Sync object /** @type {import('@jest/types').Config.InitialOptions} */ const config = { @@ -36,8 +35,7 @@ module.exports = async () => { Or through TypeScript (if `ts-node` is installed): -```ts -// jest.config.ts +```ts title="jest.config.ts" import type {Config} from '@jest/types'; // Sync object @@ -73,8 +71,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -99,8 +96,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -387,9 +383,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -447,8 +441,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -456,8 +449,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -708,8 +700,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -787,8 +778,7 @@ For example, if you want to respect Browserify's [`"browser"` field](https://git } ``` -```js -// resolver.js +```js title="resolver.js" const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; @@ -1235,8 +1225,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/website/versioned_docs/version-26.x/Es6ClassMocks.md b/website/versioned_docs/version-26.x/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/website/versioned_docs/version-26.x/Es6ClassMocks.md +++ b/website/versioned_docs/version-26.x/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/website/versioned_docs/version-26.x/GettingStarted.md b/website/versioned_docs/version-26.x/GettingStarted.md index 485ef726092b..423b1e4c42b6 100644 --- a/website/versioned_docs/version-26.x/GettingStarted.md +++ b/website/versioned_docs/version-26.x/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```js title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/website/versioned_docs/version-26.x/JestObjectAPI.md b/website/versioned_docs/version-26.x/JestObjectAPI.md index e7d8808d33c8..e8deade705cd 100644 --- a/website/versioned_docs/version-26.x/JestObjectAPI.md +++ b/website/versioned_docs/version-26.x/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -102,8 +98,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -112,8 +107,7 @@ export default { }; ``` -```js -// __tests__/createMockFromModule.test.js +```js title="__tests__/createMockFromModule.test.js" const utils = jest.createMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -147,8 +141,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -178,8 +171,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.createMockFromModule('./example'); test('should run example code', () => { @@ -220,11 +212,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/website/versioned_docs/version-26.x/JestPlatform.md b/website/versioned_docs/version-26.x/JestPlatform.md index 3066711bc5e0..429b1172c8bb 100644 --- a/website/versioned_docs/version-26.x/JestPlatform.md +++ b/website/versioned_docs/version-26.x/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `JestWorker` that take ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/website/versioned_docs/version-26.x/ManualMocks.md b/website/versioned_docs/version-26.x/ManualMocks.md index d481a5712e49..178226d727f9 100644 --- a/website/versioned_docs/version-26.x/ManualMocks.md +++ b/website/versioned_docs/version-26.x/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/website/versioned_docs/version-26.x/MockFunctionAPI.md b/website/versioned_docs/version-26.x/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/website/versioned_docs/version-26.x/MockFunctionAPI.md +++ b/website/versioned_docs/version-26.x/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/website/versioned_docs/version-26.x/MockFunctions.md b/website/versioned_docs/version-26.x/MockFunctions.md index 873dfff9462a..d583d55bdca8 100644 --- a/website/versioned_docs/version-26.x/MockFunctions.md +++ b/website/versioned_docs/version-26.x/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/website/versioned_docs/version-26.x/Puppeteer.md b/website/versioned_docs/version-26.x/Puppeteer.md index c0b92dfd97dd..65c78ff9faab 100644 --- a/website/versioned_docs/version-26.x/Puppeteer.md +++ b/website/versioned_docs/version-26.x/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/website/versioned_docs/version-26.x/TimerMocks.md b/website/versioned_docs/version-26.x/TimerMocks.md index ff8a16ef988a..8086ccd10b8b 100644 --- a/website/versioned_docs/version-26.x/TimerMocks.md +++ b/website/versioned_docs/version-26.x/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -64,8 +62,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -85,8 +82,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -124,8 +120,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/website/versioned_docs/version-26.x/TutorialAsync.md b/website/versioned_docs/version-26.x/TutorialAsync.md index dd8a2da77977..0534aec12667 100644 --- a/website/versioned_docs/version-26.x/TutorialAsync.md +++ b/website/versioned_docs/version-26.x/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/website/versioned_docs/version-26.x/TutorialReact.md b/website/versioned_docs/version-26.x/TutorialReact.md index d6be521ae589..39d0eaa01018 100644 --- a/website/versioned_docs/version-26.x/TutorialReact.md +++ b/website/versioned_docs/version-26.x/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/website/versioned_docs/version-26.x/TutorialReactNative.md b/website/versioned_docs/version-26.x/TutorialReactNative.md index beabd0d09e2d..18b740a54290 100644 --- a/website/versioned_docs/version-26.x/TutorialReactNative.md +++ b/website/versioned_docs/version-26.x/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/website/versioned_docs/version-26.x/WatchPlugins.md b/website/versioned_docs/version-26.x/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/website/versioned_docs/version-26.x/WatchPlugins.md +++ b/website/versioned_docs/version-26.x/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/website/versioned_docs/version-26.x/Webpack.md b/website/versioned_docs/version-26.x/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/website/versioned_docs/version-26.x/Webpack.md +++ b/website/versioned_docs/version-26.x/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], diff --git a/website/versioned_docs/version-27.0/BypassingModuleMocks.md b/website/versioned_docs/version-27.0/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/website/versioned_docs/version-27.0/BypassingModuleMocks.md +++ b/website/versioned_docs/version-27.0/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/website/versioned_docs/version-27.0/CodeTransformation.md b/website/versioned_docs/version-27.0/CodeTransformation.md index a7a71094f728..5cbc85a945d6 100644 --- a/website/versioned_docs/version-27.0/CodeTransformation.md +++ b/website/versioned_docs/version-27.0/CodeTransformation.md @@ -138,8 +138,7 @@ While `babel-jest` by default will transpile TypeScript files, Babel will not ve Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -149,9 +148,7 @@ module.exports = { }; ``` -```js -// jest.config.js - +```js title="jest.config.js" module.exports = { transform: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': diff --git a/website/versioned_docs/version-27.0/Configuration.md b/website/versioned_docs/version-27.0/Configuration.md index 6a3f6f66cb96..233542c2daed 100644 --- a/website/versioned_docs/version-27.0/Configuration.md +++ b/website/versioned_docs/version-27.0/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" // Sync object /** @type {import('@jest/types').Config.InitialOptions} */ const config = { @@ -36,8 +35,7 @@ module.exports = async () => { Or through TypeScript (if `ts-node` is installed): -```ts -// jest.config.ts +```ts title="jest.config.ts" import type {Config} from '@jest/types'; // Sync object @@ -73,8 +71,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -99,8 +96,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -404,9 +400,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -464,8 +458,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -473,8 +466,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -735,8 +727,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -814,8 +805,7 @@ For example, if you want to respect Browserify's [`"browser"` field](https://git } ``` -```js -// resolver.js +```js title="resolver.js" const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; @@ -1262,8 +1252,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/website/versioned_docs/version-27.0/Es6ClassMocks.md b/website/versioned_docs/version-27.0/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/website/versioned_docs/version-27.0/Es6ClassMocks.md +++ b/website/versioned_docs/version-27.0/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/website/versioned_docs/version-27.0/GettingStarted.md b/website/versioned_docs/version-27.0/GettingStarted.md index 485ef726092b..423b1e4c42b6 100644 --- a/website/versioned_docs/version-27.0/GettingStarted.md +++ b/website/versioned_docs/version-27.0/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```js title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/website/versioned_docs/version-27.0/JestObjectAPI.md b/website/versioned_docs/version-27.0/JestObjectAPI.md index 4f9c95cab35c..630e20b1dfc1 100644 --- a/website/versioned_docs/version-27.0/JestObjectAPI.md +++ b/website/versioned_docs/version-27.0/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -102,8 +98,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -112,8 +107,7 @@ export default { }; ``` -```js -// __tests__/createMockFromModule.test.js +```js title="__tests__/createMockFromModule.test.js" const utils = jest.createMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -147,8 +141,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -178,8 +171,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.createMockFromModule('./example'); test('should run example code', () => { @@ -220,11 +212,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/website/versioned_docs/version-27.0/JestPlatform.md b/website/versioned_docs/version-27.0/JestPlatform.md index 2273524221cd..7e638e040b63 100644 --- a/website/versioned_docs/version-27.0/JestPlatform.md +++ b/website/versioned_docs/version-27.0/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `JestWorker` that take ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/website/versioned_docs/version-27.0/ManualMocks.md b/website/versioned_docs/version-27.0/ManualMocks.md index d481a5712e49..178226d727f9 100644 --- a/website/versioned_docs/version-27.0/ManualMocks.md +++ b/website/versioned_docs/version-27.0/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/website/versioned_docs/version-27.0/MockFunctionAPI.md b/website/versioned_docs/version-27.0/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/website/versioned_docs/version-27.0/MockFunctionAPI.md +++ b/website/versioned_docs/version-27.0/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/website/versioned_docs/version-27.0/MockFunctions.md b/website/versioned_docs/version-27.0/MockFunctions.md index d6dc73b999aa..2e686a92e837 100644 --- a/website/versioned_docs/version-27.0/MockFunctions.md +++ b/website/versioned_docs/version-27.0/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/website/versioned_docs/version-27.0/Puppeteer.md b/website/versioned_docs/version-27.0/Puppeteer.md index 53c16767b74e..16ab669a9ab2 100644 --- a/website/versioned_docs/version-27.0/Puppeteer.md +++ b/website/versioned_docs/version-27.0/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/website/versioned_docs/version-27.0/TimerMocks.md b/website/versioned_docs/version-27.0/TimerMocks.md index e97e2af97709..b053c1dbdfc9 100644 --- a/website/versioned_docs/version-27.0/TimerMocks.md +++ b/website/versioned_docs/version-27.0/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -82,8 +80,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -103,8 +100,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -140,8 +136,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/website/versioned_docs/version-27.0/TutorialAsync.md b/website/versioned_docs/version-27.0/TutorialAsync.md index f9418ad6651b..9c283074cabd 100644 --- a/website/versioned_docs/version-27.0/TutorialAsync.md +++ b/website/versioned_docs/version-27.0/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/website/versioned_docs/version-27.0/TutorialReact.md b/website/versioned_docs/version-27.0/TutorialReact.md index 7cce1e08cf10..5fcfa52a098b 100644 --- a/website/versioned_docs/version-27.0/TutorialReact.md +++ b/website/versioned_docs/version-27.0/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/website/versioned_docs/version-27.0/TutorialReactNative.md b/website/versioned_docs/version-27.0/TutorialReactNative.md index d89564980791..ddb60b230c31 100644 --- a/website/versioned_docs/version-27.0/TutorialReactNative.md +++ b/website/versioned_docs/version-27.0/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/website/versioned_docs/version-27.0/WatchPlugins.md b/website/versioned_docs/version-27.0/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/website/versioned_docs/version-27.0/WatchPlugins.md +++ b/website/versioned_docs/version-27.0/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/website/versioned_docs/version-27.0/Webpack.md b/website/versioned_docs/version-27.0/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/website/versioned_docs/version-27.0/Webpack.md +++ b/website/versioned_docs/version-27.0/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], diff --git a/website/versioned_docs/version-27.1/BypassingModuleMocks.md b/website/versioned_docs/version-27.1/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/website/versioned_docs/version-27.1/BypassingModuleMocks.md +++ b/website/versioned_docs/version-27.1/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/website/versioned_docs/version-27.1/CodeTransformation.md b/website/versioned_docs/version-27.1/CodeTransformation.md index a7a71094f728..5cbc85a945d6 100644 --- a/website/versioned_docs/version-27.1/CodeTransformation.md +++ b/website/versioned_docs/version-27.1/CodeTransformation.md @@ -138,8 +138,7 @@ While `babel-jest` by default will transpile TypeScript files, Babel will not ve Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -149,9 +148,7 @@ module.exports = { }; ``` -```js -// jest.config.js - +```js title="jest.config.js" module.exports = { transform: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': diff --git a/website/versioned_docs/version-27.1/Configuration.md b/website/versioned_docs/version-27.1/Configuration.md index 6e72e76cbb70..6a0b44c1f30d 100644 --- a/website/versioned_docs/version-27.1/Configuration.md +++ b/website/versioned_docs/version-27.1/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" // Sync object /** @type {import('@jest/types').Config.InitialOptions} */ const config = { @@ -36,8 +35,7 @@ module.exports = async () => { Or through TypeScript (if `ts-node` is installed): -```ts -// jest.config.ts +```ts title="jest.config.ts" import type {Config} from '@jest/types'; // Sync object @@ -73,8 +71,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -99,8 +96,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -404,9 +400,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -464,8 +458,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -473,8 +466,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -735,8 +727,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -814,8 +805,7 @@ For example, if you want to respect Browserify's [`"browser"` field](https://git } ``` -```js -// resolver.js +```js title="resolver.js" const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; @@ -1297,8 +1287,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/website/versioned_docs/version-27.1/Es6ClassMocks.md b/website/versioned_docs/version-27.1/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/website/versioned_docs/version-27.1/Es6ClassMocks.md +++ b/website/versioned_docs/version-27.1/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/website/versioned_docs/version-27.1/GettingStarted.md b/website/versioned_docs/version-27.1/GettingStarted.md index 485ef726092b..423b1e4c42b6 100644 --- a/website/versioned_docs/version-27.1/GettingStarted.md +++ b/website/versioned_docs/version-27.1/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```js title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/website/versioned_docs/version-27.1/JestObjectAPI.md b/website/versioned_docs/version-27.1/JestObjectAPI.md index 4f9c95cab35c..630e20b1dfc1 100644 --- a/website/versioned_docs/version-27.1/JestObjectAPI.md +++ b/website/versioned_docs/version-27.1/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -102,8 +98,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -112,8 +107,7 @@ export default { }; ``` -```js -// __tests__/createMockFromModule.test.js +```js title="__tests__/createMockFromModule.test.js" const utils = jest.createMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -147,8 +141,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -178,8 +171,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.createMockFromModule('./example'); test('should run example code', () => { @@ -220,11 +212,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/website/versioned_docs/version-27.1/JestPlatform.md b/website/versioned_docs/version-27.1/JestPlatform.md index 2273524221cd..7e638e040b63 100644 --- a/website/versioned_docs/version-27.1/JestPlatform.md +++ b/website/versioned_docs/version-27.1/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `JestWorker` that take ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/website/versioned_docs/version-27.1/ManualMocks.md b/website/versioned_docs/version-27.1/ManualMocks.md index d481a5712e49..178226d727f9 100644 --- a/website/versioned_docs/version-27.1/ManualMocks.md +++ b/website/versioned_docs/version-27.1/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/website/versioned_docs/version-27.1/MockFunctionAPI.md b/website/versioned_docs/version-27.1/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/website/versioned_docs/version-27.1/MockFunctionAPI.md +++ b/website/versioned_docs/version-27.1/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/website/versioned_docs/version-27.1/MockFunctions.md b/website/versioned_docs/version-27.1/MockFunctions.md index d6dc73b999aa..2e686a92e837 100644 --- a/website/versioned_docs/version-27.1/MockFunctions.md +++ b/website/versioned_docs/version-27.1/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/website/versioned_docs/version-27.1/Puppeteer.md b/website/versioned_docs/version-27.1/Puppeteer.md index 53c16767b74e..16ab669a9ab2 100644 --- a/website/versioned_docs/version-27.1/Puppeteer.md +++ b/website/versioned_docs/version-27.1/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/website/versioned_docs/version-27.1/TimerMocks.md b/website/versioned_docs/version-27.1/TimerMocks.md index e97e2af97709..b053c1dbdfc9 100644 --- a/website/versioned_docs/version-27.1/TimerMocks.md +++ b/website/versioned_docs/version-27.1/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -82,8 +80,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -103,8 +100,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -140,8 +136,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/website/versioned_docs/version-27.1/TutorialAsync.md b/website/versioned_docs/version-27.1/TutorialAsync.md index f9418ad6651b..9c283074cabd 100644 --- a/website/versioned_docs/version-27.1/TutorialAsync.md +++ b/website/versioned_docs/version-27.1/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/website/versioned_docs/version-27.1/TutorialReact.md b/website/versioned_docs/version-27.1/TutorialReact.md index 7cce1e08cf10..5fcfa52a098b 100644 --- a/website/versioned_docs/version-27.1/TutorialReact.md +++ b/website/versioned_docs/version-27.1/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/website/versioned_docs/version-27.1/TutorialReactNative.md b/website/versioned_docs/version-27.1/TutorialReactNative.md index d89564980791..ddb60b230c31 100644 --- a/website/versioned_docs/version-27.1/TutorialReactNative.md +++ b/website/versioned_docs/version-27.1/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/website/versioned_docs/version-27.1/WatchPlugins.md b/website/versioned_docs/version-27.1/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/website/versioned_docs/version-27.1/WatchPlugins.md +++ b/website/versioned_docs/version-27.1/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/website/versioned_docs/version-27.1/Webpack.md b/website/versioned_docs/version-27.1/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/website/versioned_docs/version-27.1/Webpack.md +++ b/website/versioned_docs/version-27.1/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], diff --git a/website/versioned_docs/version-27.2/BypassingModuleMocks.md b/website/versioned_docs/version-27.2/BypassingModuleMocks.md index 5e48a05b9fb4..96dfa7462016 100644 --- a/website/versioned_docs/version-27.2/BypassingModuleMocks.md +++ b/website/versioned_docs/version-27.2/BypassingModuleMocks.md @@ -7,8 +7,7 @@ Jest allows you to mock out whole modules in your tests, which can be useful for Consider writing a test case for this `createUser` function: -```javascript -// createUser.js +```javascript title="createUser.js" import fetch from 'node-fetch'; export const createUser = async () => { diff --git a/website/versioned_docs/version-27.2/CodeTransformation.md b/website/versioned_docs/version-27.2/CodeTransformation.md index a7a71094f728..5cbc85a945d6 100644 --- a/website/versioned_docs/version-27.2/CodeTransformation.md +++ b/website/versioned_docs/version-27.2/CodeTransformation.md @@ -138,8 +138,7 @@ While `babel-jest` by default will transpile TypeScript files, Babel will not ve Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -149,9 +148,7 @@ module.exports = { }; ``` -```js -// jest.config.js - +```js title="jest.config.js" module.exports = { transform: { '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': diff --git a/website/versioned_docs/version-27.2/Configuration.md b/website/versioned_docs/version-27.2/Configuration.md index d5c9bc73328c..c3a99d18842d 100644 --- a/website/versioned_docs/version-27.2/Configuration.md +++ b/website/versioned_docs/version-27.2/Configuration.md @@ -16,8 +16,7 @@ Jest's configuration can be defined in the `package.json` file of your project, Or through JavaScript: -```js -// jest.config.js +```js title="jest.config.js" // Sync object /** @type {import('@jest/types').Config.InitialOptions} */ const config = { @@ -36,8 +35,7 @@ module.exports = async () => { Or through TypeScript (if `ts-node` is installed): -```ts -// jest.config.ts +```ts title="jest.config.ts" import type {Config} from '@jest/types'; // Sync object @@ -73,8 +71,7 @@ These options let you control Jest's behavior in your `package.json` file. The J You can retrieve Jest's default options to expand them if needed: -```js -// jest.config.js +```js title="jest.config.js" const {defaults} = require('jest-config'); module.exports = { // ... @@ -99,8 +96,7 @@ This option tells Jest that all imported modules in your tests should be mocked Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -404,9 +400,7 @@ Test files are normally ignored from collecting code coverage. With this option, For example, if you have tests in source files named with `.t.js` extension as following: -```javascript -// sum.t.js - +```javascript title="sum.t.js" export function sum(a, b) { return a + b; } @@ -464,8 +458,7 @@ _Note: While code transformation is applied to the linked setup-file, Jest will Example: -```js -// setup.js +```js title="setup.js" module.exports = async () => { // ... // Set reference to mongod in order to close the server during teardown. @@ -473,8 +466,7 @@ module.exports = async () => { }; ``` -```js -// teardown.js +```js title="teardown.js" module.exports = async function () { await global.__MONGOD__.stop(); }; @@ -735,8 +727,7 @@ Custom reporter modules must define a class that takes a `GlobalConfig` and repo Example reporter: -```js -// my-custom-reporter.js +```js title="my-custom-reporter.js" class MyCustomReporter { constructor(globalConfig, options) { this._globalConfig = globalConfig; @@ -816,8 +807,7 @@ For example, if you want to respect Browserify's [`"browser"` field](https://git } ``` -```js -// resolver.js +```js title="resolver.js" const browserResolve = require('browser-resolve'); module.exports = browserResolve.sync; @@ -1301,8 +1291,7 @@ Example: Sort test path alphabetically. -```js -// testSequencer.js +```js title="testSequencer.js" const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { diff --git a/website/versioned_docs/version-27.2/Es6ClassMocks.md b/website/versioned_docs/version-27.2/Es6ClassMocks.md index 334e98a8a83f..37d26d744624 100644 --- a/website/versioned_docs/version-27.2/Es6ClassMocks.md +++ b/website/versioned_docs/version-27.2/Es6ClassMocks.md @@ -11,8 +11,7 @@ ES6 classes are constructor functions with some syntactic sugar. Therefore, any We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. -```javascript -// sound-player.js +```javascript title="sound-player.js" export default class SoundPlayer { constructor() { this.foo = 'bar'; @@ -24,8 +23,7 @@ export default class SoundPlayer { } ``` -```javascript -// sound-player-consumer.js +```javascript title="sound-player-consumer.js" import SoundPlayer from './sound-player'; export default class SoundPlayerConsumer { @@ -90,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -104,8 +100,7 @@ export default mock; Import the mock and the mock method shared by all instances: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -198,8 +193,7 @@ If you define an ES6 class using the same filename as the mocked class in the `_ For the contrived example, the mock might look like this: -```javascript -// __mocks__/sound-player.js +```javascript title="__mocks__/sound-player.js" export default class SoundPlayer { constructor() { console.log('Mock SoundPlayer: constructor was called'); @@ -297,9 +291,7 @@ jest.mock('./sound-player', () => { The manual mock equivalent of this would be: -```javascript -// __mocks__/sound-player.js - +```javascript title="__mocks__/sound-player.js" // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { @@ -326,8 +318,7 @@ beforeEach(() => { Here's a complete test file which uses the module factory parameter to `jest.mock`: -```javascript -// sound-player-consumer.test.js +```javascript title="sound-player-consumer.test.js" import SoundPlayer from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; diff --git a/website/versioned_docs/version-27.2/GettingStarted.md b/website/versioned_docs/version-27.2/GettingStarted.md index 485ef726092b..423b1e4c42b6 100644 --- a/website/versioned_docs/version-27.2/GettingStarted.md +++ b/website/versioned_docs/version-27.2/GettingStarted.md @@ -89,8 +89,7 @@ yarn add --dev babel-jest @babel/core @babel/preset-env Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = { presets: [['@babel/preset-env', {targets: {node: 'current'}}]], }; @@ -102,8 +101,7 @@ _The ideal configuration for Babel will depend on your project._ See [Babel's do Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. -```javascript -// babel.config.js +```javascript title="babel.config.js" module.exports = api => { const isTest = api.env('test'); // You can use isTest to determine what presets and plugins to use. @@ -116,8 +114,7 @@ module.exports = api => { > 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: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { transform: {}, }; @@ -160,12 +157,12 @@ yarn add --dev @babel/preset-typescript Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. -```diff -// babel.config.js +```js title="babel.config.js" module.exports = { presets: [ ['@babel/preset-env', {targets: {node: 'current'}}], -+ '@babel/preset-typescript', + // highlight-next-line + '@babel/preset-typescript', ], }; ``` diff --git a/website/versioned_docs/version-27.2/JestObjectAPI.md b/website/versioned_docs/version-27.2/JestObjectAPI.md index 4f9c95cab35c..630e20b1dfc1 100644 --- a/website/versioned_docs/version-27.2/JestObjectAPI.md +++ b/website/versioned_docs/version-27.2/JestObjectAPI.md @@ -25,8 +25,7 @@ Jest configuration: Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -34,8 +33,7 @@ export default { }; ``` -```js -// __tests__/disableAutomocking.js +```js title="__tests__/disableAutomocking.js" import utils from '../utils'; jest.disableAutomock(); @@ -65,8 +63,7 @@ Returns the `jest` object for chaining. Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -75,8 +72,7 @@ export default { }; ``` -```js -// __tests__/enableAutomocking.js +```js title="__tests__/enableAutomocking.js" jest.enableAutomock(); import utils from '../utils'; @@ -102,8 +98,7 @@ This is useful when you want to create a [manual mock](ManualMocks.md) that exte Example: -```js -// utils.js +```js title="utils.js" export default { authorize: () => { return 'token'; @@ -112,8 +107,7 @@ export default { }; ``` -```js -// __tests__/createMockFromModule.test.js +```js title="__tests__/createMockFromModule.test.js" const utils = jest.createMockFromModule('../utils').default; utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); @@ -147,8 +141,7 @@ Creates a new property with the same primitive value as the original property. Example: -```js -// example.js +```js title="example.js" module.exports = { function: function square(a, b) { return a * b; @@ -178,8 +171,7 @@ module.exports = { }; ``` -```js -// __tests__/example.test.js +```js title="__tests__/example.test.js" const example = jest.createMockFromModule('./example'); test('should run example code', () => { @@ -220,11 +212,11 @@ test('should run example code', () => { Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: -```js -// banana.js +```js title="banana.js" module.exports = () => 'banana'; +``` -// __tests__/test.js +```js title="__tests__/test.js" jest.mock('../banana'); const banana = require('../banana'); // banana will be explicitly mocked. diff --git a/website/versioned_docs/version-27.2/JestPlatform.md b/website/versioned_docs/version-27.2/JestPlatform.md index 2273524221cd..7e638e040b63 100644 --- a/website/versioned_docs/version-27.2/JestPlatform.md +++ b/website/versioned_docs/version-27.2/JestPlatform.md @@ -123,9 +123,7 @@ Module used for parallelization of tasks. Exports a class `JestWorker` that take ### Example -```javascript -// heavy-task.js - +```javascript title="heavy-task.js" module.exports = { myHeavyTask: args => { // long running CPU intensive task. @@ -133,9 +131,7 @@ module.exports = { }; ``` -```javascript -// main.js - +```javascript title="main.js" async function main() { const worker = new Worker(require.resolve('./heavy-task.js')); diff --git a/website/versioned_docs/version-27.2/ManualMocks.md b/website/versioned_docs/version-27.2/ManualMocks.md index d481a5712e49..178226d727f9 100644 --- a/website/versioned_docs/version-27.2/ManualMocks.md +++ b/website/versioned_docs/version-27.2/ManualMocks.md @@ -40,8 +40,7 @@ When a manual mock exists for a given module, Jest's module system will use that 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. -```javascript -// FileSummarizer.js +```javascript title="FileSummarizer.js" 'use strict'; const fs = require('fs'); @@ -58,8 +57,7 @@ exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: -```javascript -// __mocks__/fs.js +```javascript title="__mocks__/fs.js" 'use strict'; const path = require('path'); @@ -96,8 +94,7 @@ 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: -```javascript -// __tests__/FileSummarizer-test.js +```javascript title="__tests__/FileSummarizer-test.js" 'use strict'; jest.mock('fs'); diff --git a/website/versioned_docs/version-27.2/MockFunctionAPI.md b/website/versioned_docs/version-27.2/MockFunctionAPI.md index 6010aaf573f6..b32c3827ae6e 100644 --- a/website/versioned_docs/version-27.2/MockFunctionAPI.md +++ b/website/versioned_docs/version-27.2/MockFunctionAPI.md @@ -131,13 +131,13 @@ mockFn.mock.calls[1][0] === 1; // true `mockImplementation` can also be used to mock class constructors: -```js -// SomeClass.js +```js title="SomeClass.js" module.exports = class SomeClass { m(a, b) {} }; +``` -// OtherModule.test.js +```js title="OtherModule.test.js" jest.mock('./SomeClass'); // this happens automatically with automocking const SomeClass = require('./SomeClass'); const mMock = jest.fn(); diff --git a/website/versioned_docs/version-27.2/MockFunctions.md b/website/versioned_docs/version-27.2/MockFunctions.md index d6dc73b999aa..2e686a92e837 100644 --- a/website/versioned_docs/version-27.2/MockFunctions.md +++ b/website/versioned_docs/version-27.2/MockFunctions.md @@ -115,8 +115,7 @@ Most real-world examples actually involve getting ahold of a mock function on a Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: -```js -// users.js +```js title="users.js" import axios from 'axios'; class Users { @@ -132,8 +131,7 @@ Now, in order to test this method without actually hitting the API (and thus cre Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. -```js -// users.test.js +```js title="users.test.js" import axios from 'axios'; import Users from './users'; @@ -155,8 +153,7 @@ test('should fetch users', () => { Subsets of a module can be mocked and the rest of the module can keep their actual implementation: -```js -// foo-bar-baz.js +```js title="foo-bar-baz.js" export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; @@ -201,13 +198,13 @@ myMockFn((err, val) => console.log(val)); The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: -```js -// foo.js +```js title="foo.js" module.exports = function () { // some implementation; }; +``` -// test.js +```js title="test.js" jest.mock('../foo'); // this happens automatically with automocking const foo = require('../foo'); diff --git a/website/versioned_docs/version-27.2/Puppeteer.md b/website/versioned_docs/version-27.2/Puppeteer.md index 53c16767b74e..16ab669a9ab2 100644 --- a/website/versioned_docs/version-27.2/Puppeteer.md +++ b/website/versioned_docs/version-27.2/Puppeteer.md @@ -53,8 +53,7 @@ You can also hook up puppeteer from scratch. The basic idea is to: Here's an example of the GlobalSetup script -```js -// setup.js +```js title="setup.js" const {mkdir, writeFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -76,8 +75,7 @@ module.exports = async function () { Then we need a custom Test Environment for puppeteer -```js -// puppeteer_environment.js +```js title="puppeteer_environment.js" const {readFile} = require('fs').promises; const os = require('os'); const path = require('path'); @@ -119,8 +117,7 @@ module.exports = PuppeteerEnvironment; Finally, we can close the puppeteer instance and clean-up the file -```js -// teardown.js +```js title="teardown.js" const fs = require('fs').promises; const os = require('os'); const path = require('path'); @@ -137,8 +134,7 @@ module.exports = async function () { With all the things set up, we can now write our tests like this: -```js -// test.js +```js title="test.js" const timeout = 5000; describe( diff --git a/website/versioned_docs/version-27.2/TimerMocks.md b/website/versioned_docs/version-27.2/TimerMocks.md index e97e2af97709..b053c1dbdfc9 100644 --- a/website/versioned_docs/version-27.2/TimerMocks.md +++ b/website/versioned_docs/version-27.2/TimerMocks.md @@ -5,8 +5,7 @@ title: Timer Mocks The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { @@ -20,8 +19,7 @@ function timerGame(callback) { module.exports = timerGame; ``` -```javascript -// __tests__/timerGame-test.js +```javascript title="__tests__/timerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -82,8 +80,7 @@ test('calls the callback after 1 second', () => { There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: -```javascript -// infiniteTimerGame.js +```javascript title="infiniteTimerGame.js" 'use strict'; function infiniteTimerGame(callback) { @@ -103,8 +100,7 @@ function infiniteTimerGame(callback) { module.exports = infiniteTimerGame; ``` -```javascript -// __tests__/infiniteTimerGame-test.js +```javascript title="__tests__/infiniteTimerGame-test.js" 'use strict'; jest.useFakeTimers(); @@ -140,8 +136,7 @@ describe('infiniteTimerGame', () => { Another possibility is use `jest.advanceTimersByTime(msToRun)`. 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 during 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. -```javascript -// timerGame.js +```javascript title="timerGame.js" 'use strict'; function timerGame(callback) { diff --git a/website/versioned_docs/version-27.2/TutorialAsync.md b/website/versioned_docs/version-27.2/TutorialAsync.md index f9418ad6651b..9c283074cabd 100644 --- a/website/versioned_docs/version-27.2/TutorialAsync.md +++ b/website/versioned_docs/version-27.2/TutorialAsync.md @@ -7,8 +7,7 @@ First, enable Babel support in Jest as documented in the [Getting Started](Getti Let's implement a module that fetches user data from an API and returns the user name. -```js -// user.js +```js title="user.js" import request from './request'; export function getUserName(userID) { @@ -20,8 +19,7 @@ In the above implementation, we expect the `request.js` module to return a promi Now imagine an implementation of `request.js` that goes to the network and fetches some user data: -```js -// request.js +```js title="request.js" const http = require('http'); export default function request(url) { @@ -40,8 +38,7 @@ export default function request(url) { Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: -```js -// __mocks__/request.js +```js title="__mocks__/request.js" const users = { 4: {name: 'Mark'}, 5: {name: 'Paul'}, @@ -63,8 +60,7 @@ export default function request(url) { Now let's write a test for our async functionality. -```js -// __tests__/user-test.js +```js title="__tests__/user-test.js" jest.mock('../request'); import * as user from '../user'; diff --git a/website/versioned_docs/version-27.2/TutorialReact.md b/website/versioned_docs/version-27.2/TutorialReact.md index 7cce1e08cf10..5fcfa52a098b 100644 --- a/website/versioned_docs/version-27.2/TutorialReact.md +++ b/website/versioned_docs/version-27.2/TutorialReact.md @@ -46,8 +46,7 @@ Your `package.json` should look something like this (where `` i } ``` -```js -// babel.config.js +```js title="babel.config.js" module.exports = { presets: ['@babel/preset-env', '@babel/preset-react'], }; @@ -59,8 +58,7 @@ module.exports = { Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: -```tsx -// Link.react.js +```tsx title="Link.react.js" import React, {useState} from 'react'; const STATUS = { @@ -98,8 +96,7 @@ export default Link; 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: -```tsx -// Link.react.test.js +```tsx title="Link.react.test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Link from '../Link.react'; @@ -127,8 +124,7 @@ test('Link changes the class when hovered', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Link.react.test.js.snap +```javascript title="__tests__/__snapshots__/Link.react.test.js.snap" exports[`Link changes the class when hovered 1`] = ` { @@ -230,8 +225,7 @@ const CheckboxWithLabel = ({labelOn, labelOff}) => { export default CheckboxWithLabel; ``` -```tsx -// __tests__/CheckboxWithLabel-test.js +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -261,9 +255,7 @@ You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. -```tsx -// __tests__/CheckboxWithLabel-test.js - +```tsx title="__tests__/CheckboxWithLabel-test.js" import React from 'react'; import {shallow} from 'enzyme'; import CheckboxWithLabel from '../CheckboxWithLabel'; @@ -286,8 +278,7 @@ The code for this example is available at [examples/enzyme](https://github.com/f 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`: -```javascript -// custom-transformer.js +```javascript title="custom-transformer.js" 'use strict'; const {transform} = require('@babel/core'); diff --git a/website/versioned_docs/version-27.2/TutorialReactNative.md b/website/versioned_docs/version-27.2/TutorialReactNative.md index d89564980791..ddb60b230c31 100644 --- a/website/versioned_docs/version-27.2/TutorialReactNative.md +++ b/website/versioned_docs/version-27.2/TutorialReactNative.md @@ -30,8 +30,7 @@ Run `yarn test` to run tests with Jest. Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: -```tsx -// Intro.js +```tsx title="Intro.js" import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; @@ -72,8 +71,7 @@ export default Intro; 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: -```tsx -// __tests__/Intro-test.js +```tsx title="__tests__/Intro-test.js" import React from 'react'; import renderer from 'react-test-renderer'; import Intro from '../Intro'; @@ -86,8 +84,7 @@ test('renders correctly', () => { When you run `yarn test` or `jest`, this will produce an output file like this: -```javascript -// __tests__/__snapshots__/Intro-test.js.snap +```javascript title="__tests__/__snapshots__/Intro-test.js.snap" exports[`Intro renders correctly 1`] = ` { Again, we create a test file in the `__tests__/` folder: -```javascript -// __tests__/displayUser-test.js +```javascript title="__tests__/displayUser-test.js" 'use strict'; jest.mock('../fetchCurrentUser'); diff --git a/website/versioned_docs/version-27.2/WatchPlugins.md b/website/versioned_docs/version-27.2/WatchPlugins.md index f501e1580a83..bcf2991083f1 100644 --- a/website/versioned_docs/version-27.2/WatchPlugins.md +++ b/website/versioned_docs/version-27.2/WatchPlugins.md @@ -24,8 +24,7 @@ class MyWatchPlugin { To connect your watch plugin to Jest, add its path under `watchPlugins` in your Jest configuration: -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: ['path/to/yourWatchPlugin'], @@ -174,8 +173,7 @@ For stability and safety reasons, only part of the global configuration keys can Plugins can be customized via your Jest configuration. -```javascript -// jest.config.js +```javascript title="jest.config.js" module.exports = { // ... watchPlugins: [ diff --git a/website/versioned_docs/version-27.2/Webpack.md b/website/versioned_docs/version-27.2/Webpack.md index e629d32a52b6..842c046f8b1c 100644 --- a/website/versioned_docs/version-27.2/Webpack.md +++ b/website/versioned_docs/version-27.2/Webpack.md @@ -9,8 +9,7 @@ Jest can be used in projects that use [webpack](https://webpack.js.org/) to mana Let's start with a common sort of webpack config file and translate it to a Jest setup. -```js -// webpack.config.js +```js title="webpack.config.js" module.exports = { module: { loaders: [ @@ -42,8 +41,7 @@ If you have JavaScript files that are transformed by Babel, you can [enable supp Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. -```json -// package.json +```json title="package.json" { "jest": { "moduleNameMapper": { @@ -56,15 +54,11 @@ Next, let's configure Jest to gracefully handle asset files such as stylesheets And the mock files themselves: -```js -// __mocks__/styleMock.js - +```js title="__mocks__/styleMock.js" module.exports = {}; ``` -```js -// __mocks__/fileMock.js - +```js title="__mocks__/fileMock.js" module.exports = 'test-file-stub'; ``` @@ -78,8 +72,7 @@ yarn add --dev identity-obj-proxy Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). -```json -// package.json (for CSS Modules) +```json title="package.json (for CSS Modules)" { "jest": { "moduleNameMapper": { @@ -94,8 +87,7 @@ Then all your className lookups on the styles object will be returned as-is (e.g If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: -```js -// fileTransformer.js +```js title="fileTransformer.js" const path = require('path'); module.exports = { @@ -105,8 +97,7 @@ module.exports = { }; ``` -```json -// package.json (for custom transformers and CSS Modules) +```json title="package.json (for custom transformers and CSS Modules)" { "jest": { "moduleNameMapper": { @@ -135,8 +126,7 @@ _Note: if you are using babel-jest with additional code preprocessors, you have Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. -```json -// package.json +```json title="package.json" { "jest": { "moduleFileExtensions": ["js", "jsx"], @@ -154,8 +144,7 @@ Now that Jest knows how to process our files, we need to tell it how to _find_ t 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. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"], @@ -171,8 +160,7 @@ Similarly, webpack's `resolve.root` option functions like setting the `NODE_PATH And finally, we have to handle the webpack `alias`. For that, we can make use of the `moduleNameMapper` option again. -```json -// package.json +```json title="package.json" { "jest": { "modulePaths": ["/shared/vendor/modules"],