Skip to content

Commit 306c467

Browse files
delbaoliveiratimneutkensleerobstefanprobstmolebox
authored
Update Jest examples and docs (vercel#31633)
Co-authored-by: Tim Neutkens <[email protected]> Co-authored-by: Lee Robinson <[email protected]> Co-authored-by: stefanprobst <[email protected]> Co-authored-by: Rich Haines <[email protected]>
1 parent b01a6ba commit 306c467

File tree

26 files changed

+832
-74
lines changed

26 files changed

+832
-74
lines changed

docs/testing.md

Lines changed: 71 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Jest, and React Testing Library.
2+
description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.
33
---
44

55
# Testing
@@ -243,55 +243,96 @@ You can learn more about Playwright and Continuous Integration from these resour
243243

244244
## Jest and React Testing Library
245245

246-
Jest and React Testing Library are frequently used together for **Unit Testing**.
246+
Jest and React Testing Library are frequently used together for **Unit Testing**. There are three ways you can start using Jest within your Next.js application:
247+
248+
1. Using one of our [quickstart examples](https://nextjs.org/docs/testing#quickstart-2)
249+
2. With the [Next.js Rust Compiler](https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler)
250+
3. With [Babel](https://nextjs.org/docs/testing#setting-up-jest-with-babel)
251+
252+
The following sections will go through how you can set up Jest with each of these options:
247253

248254
### Quickstart
249255

250-
You can use `create-next-app` with the [with-jest example](https://github.com/vercel/next.js/tree/canary/examples/with-jest) to quickly get started with Jest and React Testing Library:
256+
You can use `create-next-app` with the [with-jest](https://github.com/vercel/next.js/tree/canary/examples/with-jest) example to quickly get started with Jest and React Testing Library:
251257

252258
```bash
253259
npx create-next-app@latest --example with-jest with-jest-app
254260
```
255261

256-
### Manual setup
262+
### Setting up Jest (with the Rust Compiler)
263+
264+
Since the release of [Next.js 12](https://nextjs.org/blog/next-12), Next.js now has built-in configuration for Jest.
257265

258-
To manually set up Jest and React Testing Library, install `jest` , `@testing-library/react`, `@testing-library/jest-dom` as well as some supporting packages:
266+
To set up Jest, install `jest` , `@testing-library/react`, `@testing-library/jest-dom` and `react-test-renderer`:
259267

260268
```bash
261-
npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom identity-obj-proxy react-test-renderer
269+
npm install --save-dev jest @testing-library/react @testing-library/jest-dom react-test-renderer
262270
```
263271

264-
**Configuring Jest**
265-
266-
Create a `jest.config.js` file in your project's root directory and add the following configuration options:
272+
Create a `jest.config.js` file in your project's root directory and add the following:
267273

268274
```jsx
269275
// jest.config.js
276+
const nextJest = require('next/jest')
277+
278+
const createJestConfig = nextJest({
279+
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
280+
dir: './',
281+
})
282+
283+
// Add any custom config to be passed to Jest
284+
const customJestConfig = {
285+
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
286+
}
287+
288+
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
289+
module.exports = createJestConfig(customJestConfig)
290+
```
291+
292+
Under the hood, `next/jest` is automatically configuring Jest for you, including:
293+
294+
- Setting up `transform` using [SWC](https://nextjs.org/docs/advanced-features/compiler)
295+
- Auto mocking stylesheets (`.css`, `.module.css`, and their scss variants) and image imports
296+
- Loading `.env` (and all variants) into `process.env`
297+
- Ignoring `node_modules` from test resolving and transforms
298+
- Ignoring `.next` from test resolving
299+
- Loading `next.config.js` for flags that enable SWC transforms
300+
301+
### Setting up Jest (with Babel)
302+
303+
If you opt-out of the [Rust Compiler](https://nextjs.org/docs/advanced-features/compiler), you will need to manually configure Jest and install `babel-jest` and `identity-obj-proxy` in addition to the packages above.
270304

305+
Here are the recommended options to configure Jest for Next.js:
306+
307+
```jsx
308+
// jest.config.js
271309
module.exports = {
272310
collectCoverageFrom: [
273311
'**/*.{js,jsx,ts,tsx}',
274312
'!**/*.d.ts',
275313
'!**/node_modules/**',
276314
],
277315
moduleNameMapper: {
278-
/* Handle CSS imports (with CSS modules)
279-
https://jestjs.io/docs/webpack#mocking-css-modules */
316+
// Handle CSS imports (with CSS modules)
317+
// https://jestjs.io/docs/webpack#mocking-css-modules
280318
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
281319

282320
// Handle CSS imports (without CSS modules)
283321
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
284322

285-
/* Handle image imports
286-
https://jestjs.io/docs/webpack#handling-static-assets */
287-
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$':
288-
'<rootDir>/__mocks__/fileMock.js',
323+
// Handle image imports
324+
// https://jestjs.io/docs/webpack#handling-static-assets
325+
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': `<rootDir>/__mocks__/fileMock.js`,
326+
327+
// Handle module aliases
328+
'^@/components/(.*)$': '<rootDir>/components/$1',
289329
},
330+
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
290331
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
291332
testEnvironment: 'jsdom',
292333
transform: {
293-
/* Use babel-jest to transpile tests with the next/babel preset
294-
https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object */
334+
// Use babel-jest to transpile tests with the next/babel preset
335+
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
295336
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
296337
},
297338
transformIgnorePatterns: [
@@ -301,55 +342,50 @@ module.exports = {
301342
}
302343
```
303344

304-
You can learn more about each option above in the [Jest docs](https://jestjs.io/docs/configuration).
345+
You can learn more about each configuration option in the [Jest docs](https://jestjs.io/docs/configuration).
305346

306347
**Handling stylesheets and image imports**
307348

308-
These files aren't useful in tests but importing them may cause errors, so we will need to mock them. Create the mock files we referenced in the configuration above - `fileMock.js` and `styleMock.js` - inside a `__mocks__` directory:
349+
Styleheets and images aren't used in the tests but importing them may cause errors, so they will need to be mocked. Create the mock files referenced in the configuration above - `fileMock.js` and `styleMock.js` - inside a `__mocks__` directory:
309350

310-
```json
351+
```js
311352
// __mocks__/fileMock.js
312-
313-
(module.exports = "test-file-stub")
353+
module.exports = 'test-file-stub'
314354
```
315355

316-
```json
356+
```js
317357
// __mocks__/styleMock.js
318-
319-
module.exports = {};
358+
module.exports = {}
320359
```
321360

322361
If you're running into the issue `"Failed to parse src "test-file-stub" on 'next/image'"`, add a '/' to your fileMock.
323362

324-
```json
363+
```js
325364
// __mocks__/fileMock.js
326-
327-
(module.exports = "/test-file-stub")
365+
module.exports = '/test-file-stub'
328366
```
329367

330368
For more information on handling static assets, please refer to the [Jest Docs](https://jestjs.io/docs/webpack#handling-static-assets).
331369

332-
**Extend Jest with custom matchers**
370+
**Optional: Extend Jest with custom matchers**
333371

334372
`@testing-library/jest-dom` includes a set of convenient [custom matchers](https://github.com/testing-library/jest-dom#custom-matchers) such as `.toBeInTheDocument()` making it easier to write tests. You can import the custom matchers for every test by adding the following option to the Jest configuration file:
335373

336-
```json
374+
```js
337375
// jest.config.js
338-
339376
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
340377
```
341378

342379
Then, inside `jest.setup.js`, add the following import:
343380

344381
```jsx
345382
// jest.setup.js
346-
347383
import '@testing-library/jest-dom/extend-expect'
348384
```
349385

350386
If you need to add more setup options before each test, it's common to add them to the `jest.setup.js` file above.
351387

352-
**Absolute Imports and Module Path Aliases**
388+
**Optional: Absolute Imports and Module Path Aliases**
353389

354390
If your project is using [Module Path Aliases](https://nextjs.org/docs/advanced-features/module-path-aliases), you will need to configure Jest to resolve the imports by matching the paths option in the `jsconfig.json` file with the `moduleNameMapper` option in the `jest.config.js` file. For example:
355391

@@ -372,6 +408,8 @@ moduleNameMapper: {
372408
}
373409
```
374410

411+
### Creating your tests:
412+
375413
**Add a test script to package.json**
376414

377415
Add the Jest executable in watch mode to the `package.json` scripts:
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"root": true,
3+
"extends": ["next/core-web-vitals"],
4+
"plugins": ["testing-library"],
5+
"overrides": [
6+
// Only uses Testing Library lint rules in test files
7+
{
8+
"files": [
9+
"**/__tests__/**/*.[jt]s?(x)",
10+
"**/?(*.)+(spec|test).[jt]s?(x)"
11+
],
12+
"extends": ["plugin:testing-library/react"]
13+
}
14+
]
15+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# next.js
12+
/.next/
13+
/out/
14+
15+
# production
16+
/build
17+
18+
# misc
19+
.DS_Store
20+
*.pem
21+
22+
# debug
23+
npm-debug.log*
24+
yarn-debug.log*
25+
yarn-error.log*
26+
27+
# local env files
28+
.env.local
29+
.env.development.local
30+
.env.test.local
31+
.env.production.local
32+
33+
# vercel
34+
.vercel

examples/with-jest-babel/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Next.js + Jest
2+
3+
This example shows how to configure Jest to work with Next.js and Babel. Since the release of Next.js 12, Next.js has in-built configuration for Jest with SWC. See the [with-jest](https://github.com/vercel/next.js/tree/canary/examples/with-jest) example for the latest implementation.
4+
5+
This includes Next.js' built-in support for Global CSS, CSS Modules, and TypeScript!
6+
7+
## How to Use
8+
9+
Quickly get started using [Create Next App](https://github.com/vercel/next.js/tree/canary/packages/create-next-app#readme)!
10+
11+
In your terminal, run the following command:
12+
13+
```bash
14+
npx create-next-app --example with-jest with-jest-app
15+
# or
16+
yarn create next-app --example with-jest with-jest-app
17+
```
18+
19+
## Run Jest Tests
20+
21+
```bash
22+
npm test
23+
```
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)