如何使用 Next.js 設定 Jest
Jest 和 React Testing Library 經常一起用於單元測試和快照測試。本指南將向您展示如何使用 Next.js 設定 Jest 並編寫您的第一個測試。
須知:由於
async伺服器元件是 React 生態系統的新功能,Jest 目前不支援它們。雖然您仍然可以對同步伺服器和客戶端元件執行單元測試,但我們建議對async元件使用端到端測試。
快速入門
您可以使用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 @types/jest
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest執行以下命令生成一個基本的 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新增測試指令碼
最後,向您的package.json檔案新增一個 Jest test指令碼
{
"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 - 使用良好的測試實踐來匹配元素。
這有幫助嗎?