使用 Next.js 設定 Jest
Jest 和 React Testing Library 經常一起用於單元測試和快照測試。本指南將向您展示如何使用 Next.js 設定 Jest 並編寫您的第一個測試。
小知識: 由於
async
伺服器元件是 React 生態系統的新功能,因此 Jest 目前不支援它們。雖然您仍然可以為同步伺服器和用戶端元件執行單元測試,但我們建議對async
元件使用 E2E 測試。
快速開始
您可以使用 create-next-app
和 Next.js with-jest 範例快速開始
npx create-next-app@latest --example with-jest with-jest-app
手動設定
自從 Next.js 12 發布以來,Next.js 現在已內建 Jest 的設定。
若要設定 Jest,請安裝 jest
和以下套件作為開發依賴項
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node
執行以下命令以產生基本的 Jest 設定檔
npm init jest@latest
# or
yarn create jest@latest
# or
pnpm create jest@latest
這將引導您完成一系列提示,為您的專案設定 Jest,包括自動建立 jest.config.ts|js
檔案。
更新您的設定檔以使用 next/jest
。此轉換器具有所有必要的設定選項,可讓 Jest 與 Next.js 搭配運作
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
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 config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)
在底層,next/jest
會自動為您設定 Jest,包括
- 使用 Next.js 編譯器設定
transform
。 - 自動模擬樣式表 (
.css
、.module.css
和其 scss 變體)、圖片匯入和next/font
。 - 將
.env
(和所有變體) 載入到process.env
中。 - 從測試解析和轉換中忽略
node_modules
。 - 從測試解析中忽略
.next
。 - 載入
next.config.js
以取得啟用 SWC 轉換的標誌。
小知識:若要直接測試環境變數,請在個別的設定腳本或您的
jest.config.ts
檔案中手動載入它們。如需更多資訊,請參閱測試環境變數。
選用:處理絕對路徑匯入和模組路徑別名
如果您的專案使用模組路徑別名,您將需要設定 Jest 以解析匯入,方法是將 jsconfig.json
檔案中的 paths
選項與 jest.config.js
檔案中的 moduleNameMapper
選項進行匹配。例如
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}
選用:使用自訂匹配器擴充 Jest
@testing-library/jest-dom
包含一組方便的自訂匹配器,例如 .toBeInTheDocument()
,讓編寫測試更容易。您可以將自訂匹配器匯入到每個測試中,方法是將以下選項新增至 Jest 設定檔
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
然後,在 jest.setup
內,新增以下匯入
import '@testing-library/jest-dom'
小知識:
extend-expect
已在v6.0
中移除,因此如果您使用的是版本 6 之前的@testing-library/jest-dom
,您將需要改為匯入@testing-library/jest-dom/extend-expect
。
如果您需要在每個測試之前新增更多設定選項,您可以將它們新增至上方的 jest.setup
檔案。
將測試腳本新增至 package.json
最後,將 Jest test
腳本新增至您的 package.json
檔案
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}
jest --watch
將在檔案變更時重新執行測試。如需更多 Jest CLI 選項,請參閱 Jest 文件。
建立您的第一個測試
您的專案現在已準備好執行測試。在您專案的根目錄中建立一個名為 __tests__
的資料夾。
例如,我們可以新增一個測試來檢查 <Page />
元件是否成功渲染標題
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'
describe('Page', () => {
it('renders a heading', () => {
render(<Page />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
或者,新增快照測試以追蹤元件中任何非預期的變更
import { render } from '@testing-library/react'
import Page from '../app/page'
it('renders homepage unchanged', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})
執行您的測試
然後,執行以下命令以執行您的測試
npm run test
# or
yarn test
# or
pnpm test
其他資源
若要深入閱讀,您可能會發現這些資源很有幫助
- Next.js 與 Jest 範例
- Jest 文件
- React Testing Library 文件
- Testing Playground - 使用良好的測試實務來匹配元素。
這有幫助嗎?