如何在 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 @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(使用 Babel)
如果您選擇不使用 Next.js 編譯器而改用 Babel,則除了上述軟體包之外,還需要手動配置 Jest 並安裝 babel-jest 和 identity-obj-proxy。
以下是為 Next.js 配置 Jest 的推薦選項。
module.exports = {
collectCoverage: true,
// on node 14.x coverage provider v8 offers good speed and more or less good report
coverageProvider: 'v8',
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
'!<rootDir>/out/**',
'!<rootDir>/.next/**',
'!<rootDir>/*.config.js',
'!<rootDir>/coverage/**',
],
moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jest.nodejs.com.tw/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://jest.nodejs.com.tw/docs/webpack#handling-static-assets
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
'^@/components/(.*)$': '<rootDir>/components/$1',
// Handle @next/font
'@next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// Handle next/font
'next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// Disable server-only
'server-only': `<rootDir>/__mocks__/empty.js`,
},
// Add more setup options before each test is run
// 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://jest.nodejs.com.tw/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
}您可以在 Jest 文件中瞭解更多關於每個配置選項的資訊。我們還建議查閱 next/jest 配置,以瞭解 Next.js 如何配置 Jest。
處理樣式表和圖片匯入
樣式表和影像不會在測試中使用,但匯入它們可能會導致錯誤,因此需要模擬它們。
在 __mocks__ 目錄中建立上面配置中引用的模擬檔案——fileMock.js 和 styleMock.js。
module.exports = 'test-file-stub'module.exports = {}有關處理靜態資源的更多資訊,請參閱 Jest 文件。
處理字型
要處理字型,請在 __mocks__ 目錄中建立 nextFontMock.js 檔案,並新增以下配置。
module.exports = new Proxy(
{},
{
get: function getter() {
return () => ({
className: 'className',
variable: 'variable',
style: { fontFamily: 'fontFamily' },
})
},
}
)可選:處理絕對匯入和模組路徑別名
如果您的專案正在使用 模組路徑別名,您將需要配置 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__ 的資料夾。
例如,我們可以新增一個測試來檢查 <Home /> 元件是否成功渲染了一個標題。
export default function Home() {
return <h1>Home</h1>
}import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
describe('Home', () => {
it('renders a heading', () => {
render(<Home />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})可選地,新增一個 快照測試,以跟蹤元件中任何意外的更改。
import { render } from '@testing-library/react'
import Home from '../pages/index'
it('renders homepage unchanged', () => {
const { container } = render(<Home />)
expect(container).toMatchSnapshot()
})須知:測試檔案不應包含在 Pages 路由器中,因為 Pages 路由器中的任何檔案都被視為路由。
執行你的測試
然後,執行以下命令來執行你的測試
npm run test
# or
yarn test
# or
pnpm test其他資源
如需進一步閱讀,您可能會發現以下資源很有幫助:
- Next.js 和 Jest 示例
- Jest 文件
- React Testing Library 文件
- 測試演練場 - 使用良好的測試實踐來匹配元素。
這有幫助嗎?