Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Update Jest examples and docs #31633

Merged
merged 32 commits into from
Nov 30, 2021
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
39e4144
Rename with-jest-babel example
delbaoliveira Nov 19, 2021
04c45b5
Update README.md
delbaoliveira Nov 19, 2021
c1c0988
Update jest.config.js for new example
delbaoliveira Nov 19, 2021
67f2630
Fix line break
delbaoliveira Nov 19, 2021
026ba23
Delete mocks for SWC example
delbaoliveira Nov 19, 2021
bc38c13
Add Jest docs link
delbaoliveira Nov 19, 2021
b604725
Remove unused package and update Jest
delbaoliveira Nov 19, 2021
9bcddd4
Update docs
delbaoliveira Nov 19, 2021
cecfd40
Update comments
delbaoliveira Nov 19, 2021
b713491
Merge branch 'canary' into update-jest-example
delbaoliveira Nov 19, 2021
7b362b1
Update testing.md
delbaoliveira Nov 19, 2021
b8a4c3b
Clarify opt out sentence
delbaoliveira Nov 19, 2021
6ff455d
Update docs/testing.md
timneutkens Nov 21, 2021
fba9e83
Update docs/testing.md
delbaoliveira Nov 22, 2021
bb6ee1d
Update docs/testing.md
delbaoliveira Nov 22, 2021
deec8d0
Update docs/testing.md
delbaoliveira Nov 22, 2021
5723fe8
Update docs/testing.md
delbaoliveira Nov 22, 2021
2368ef5
Update docs/testing.md
delbaoliveira Nov 22, 2021
2a21d19
Update docs/testing.md
delbaoliveira Nov 22, 2021
39de36e
Update docs/testing.md
delbaoliveira Nov 22, 2021
9fec0a6
Change SWC to Rust Compiler and link to docs
delbaoliveira Nov 22, 2021
782a49d
Update docs/testing.md
delbaoliveira Nov 22, 2021
619ddce
Merge branch 'canary' into update-jest-example
delbaoliveira Nov 22, 2021
79f33c5
Add footer to with-jest example
delbaoliveira Nov 22, 2021
93bec37
Update snapshot
delbaoliveira Nov 22, 2021
5358520
Add footer to with-jest-babel example
delbaoliveira Nov 22, 2021
cbafca0
Update snapshot
delbaoliveira Nov 22, 2021
53bdb3f
Merge branch 'update-jest-example' of https://github.com/delbaoliveir…
delbaoliveira Nov 22, 2021
3968e9a
Add summary at the start of Jest section
delbaoliveira Nov 22, 2021
b581186
Merge branch 'canary' into update-jest-example
delbaoliveira Nov 22, 2021
e6de54f
Apply suggestions from code review
leerob Nov 29, 2021
b207f22
Merge branch 'canary' into update-jest-example
leerob Nov 29, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 71 additions & 33 deletions docs/testing.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Jest, and React Testing Library.
description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.
---

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

## Jest and React Testing Library

Jest and React Testing Library are frequently used together for **Unit Testing**.
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:

1. Using one of our [quickstart examples](https://nextjs.org/docs/testing#quickstart-2)
2. With the [Next.js Rust Compiler](https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler)
3. With [Babel](https://nextjs.org/docs/testing#setting-up-jest-with-babel)

The following sections will go through how you can set up Jest with each of these options:

### Quickstart
Copy link
Collaborator

Choose a reason for hiding this comment

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

I wonder if I'm being pedantic here, what are your thoughts on converting this into steps, using the same heading titles?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Could you expand on what you mean here? 😊

Copy link
Collaborator

Choose a reason for hiding this comment

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

Sorry. I just mean, would It be clearer for us to explain the QuickStart as a set of steps:

## Step 1: install

## Step2: do something else

This may not be the case here. I don't have a hard and fast rule on this, I just think it makes skimming content easier, you can drop in a a step if need etc.. I don't think this fits in all cases, was wondering what your thoughts are with this section.

I quite like how you have done it tbh, just raising the question. ☺️

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah, thank you! I agree with you, it's good to give people context at the start. As you said, I'm not sure how the steps would fit this case, but I've added a quick summary here. wdyt?


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

```bash
npx create-next-app@latest --example with-jest with-jest-app
```

### Manual setup
### Setting up Jest (with the Rust Compiler)

Since the release of [Next.js 12](https://nextjs.org/blog/next-12), Next.js now has built-in configuration for Jest.

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

```bash
npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom identity-obj-proxy react-test-renderer
npm install --save-dev jest @testing-library/react @testing-library/jest-dom react-test-renderer
```

**Configuring Jest**

Create a `jest.config.js` file in your project's root directory and add the following configuration options:
Create a `jest.config.js` file in your project's root directory and add the following:

```jsx
// jest.config.js
const nextJest = require('next/jest')
delbaoliveira marked this conversation as resolved.
Show resolved Hide resolved

const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})

// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)
```

Under the hood, `next/jest` is automatically configuring Jest for you, including:

- Setting up `transform` using [SWC](https://nextjs.org/docs/advanced-features/compiler)
- Auto mocking stylesheets (`.css`, `.module.css`, and their scss variants) and image imports
- Loading `.env` (and all variants) into `process.env`
- Ignoring `node_modules` from test resolving and transforms
- Ignoring `.next` from test resolving
- Loading `next.config.js` for flags that enable experimental SWC transforms
leerob marked this conversation as resolved.
Show resolved Hide resolved

### Setting up Jest (with Babel)

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.
leerob marked this conversation as resolved.
Show resolved Hide resolved

Here are the recommended options to configure Jest for Next.js:

```jsx
// jest.config.js
module.exports = {
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
],
moduleNameMapper: {
/* Handle CSS imports (with CSS modules)
https://jestjs.io/docs/webpack#mocking-css-modules */
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

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

/* Handle image imports
https://jestjs.io/docs/webpack#handling-static-assets */
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$':
'<rootDir>/__mocks__/fileMock.js',
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': `<rootDir>/__mocks__/fileMock.js`,

// Handle module aliases
'^@/components/(.*)$': '<rootDir>/components/$1',
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
testEnvironment: 'jsdom',
transform: {
/* Use babel-jest to transpile tests with the next/babel preset
https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object */
// Use babel-jest to transpile tests with the next/babel preset
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: [
Expand All @@ -301,55 +342,50 @@ module.exports = {
}
```

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

**Handling stylesheets and image imports**

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

```json
```js
// __mocks__/fileMock.js

(module.exports = "test-file-stub")
module.exports = 'test-file-stub'
```

```json
```js
// __mocks__/styleMock.js

module.exports = {};
module.exports = {}
```

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

```json
```js
// __mocks__/fileMock.js

(module.exports = "/test-file-stub")
module.exports = '/test-file-stub'
```

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

**Extend Jest with custom matchers**
**Optional: Extend Jest with custom matchers**

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

```json
```js
// jest.config.js

setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
```

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

```jsx
// jest.setup.js

import '@testing-library/jest-dom/extend-expect'
```

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

**Absolute Imports and Module Path Aliases**
**Optional: Absolute Imports and Module Path Aliases**

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:

Expand All @@ -372,6 +408,8 @@ moduleNameMapper: {
}
```

### Creating your tests:

**Add a test script to package.json**

Add the Jest executable in watch mode to the `package.json` scripts:
Expand Down
15 changes: 15 additions & 0 deletions examples/with-jest-babel/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"root": true,
"extends": ["next/core-web-vitals"],
"plugins": ["testing-library"],
"overrides": [
// Only uses Testing Library lint rules in test files
{
"files": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[jt]s?(x)"
],
"extends": ["plugin:testing-library/react"]
}
]
}
34 changes: 34 additions & 0 deletions examples/with-jest-babel/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel
23 changes: 23 additions & 0 deletions examples/with-jest-babel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Next.js + Jest

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.

This includes Next.js' built-in support for Global CSS, CSS Modules, and TypeScript!

## How to Use

Quickly get started using [Create Next App](https://github.com/vercel/next.js/tree/canary/packages/create-next-app#readme)!

In your terminal, run the following command:

```bash
npx create-next-app --example with-jest with-jest-app
# or
yarn create next-app --example with-jest with-jest-app
```

## Run Jest Tests

```bash
npm test
```
Loading