跳到內容

如何使用 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 配合工作所需的所有配置選項。

jest.config.ts
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選項匹配來解析匯入。例如:

tsconfig.json 或 jsconfig.json
{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "bundler",
    "baseUrl": "./",
    "paths": {
      "@/components/*": ["components/*"]
    }
  }
}
jest.config.js
moduleNameMapper: {
  // ...
  '^@/components/(.*)$': '<rootDir>/components/$1',
}

可選:使用自定義匹配器擴充套件 Jest

@testing-library/jest-dom包含一組方便的自定義匹配器,例如.toBeInTheDocument(),使編寫測試更容易。您可以透過將以下選項新增到 Jest 配置檔案中,為每個測試匯入自定義匹配器:

jest.config.ts
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']

然後,在jest.setup中,新增以下匯入:

jest.setup.ts
import '@testing-library/jest-dom'

須知: extend-expectv6.0中已移除,因此如果您使用的是低於 6 版本的@testing-library/jest-dom,則需要匯入@testing-library/jest-dom/extend-expect

如果您需要在每個測試之前新增更多設定選項,可以將其新增到上述jest.setup檔案中。

package.json新增測試指令碼

最後,向您的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 />元件是否成功渲染了一個標題

app/page.js
import Link from 'next/link'
 
export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
__tests__/page.test.jsx
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()
  })
})

可選地,新增一個快照測試來跟蹤元件中任何意外的更改

__tests__/snapshot.js
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

其他資源

如需進一步閱讀,您可能會發現這些資源很有幫助