在 Next.js 中設定 Jest

Jest 和 React Testing Library 常被一起用於單元測試 (Unit Testing)快照測試 (Snapshot Testing)。本指南將展示如何在 Next.js 中設定 Jest 並撰寫你的第一個測試。

須知事項: 由於 async 伺服器元件 (Server Components) 是 React 生態系統中的新功能,Jest 目前尚未支援。雖然你仍可為同步的伺服器與客戶端元件執行單元測試,但我們建議對 async 元件使用端對端測試 (E2E tests)

快速開始

你可以使用 create-next-app 搭配 Next.js 的 with-jest 範例快速開始:

Terminal
npx create-next-app@latest --example with-jest with-jest-app

手動設定

Next.js 12 發布以來,Next.js 已內建對 Jest 的配置支援。

要設定 Jest,請安裝 jest 和以下套件作為開發依賴:

Terminal
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# 或
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# 或
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

執行以下指令生成基本的 Jest 配置檔:

Terminal
npm init jest@latest
# 或
yarn create jest@latest
# 或
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({
  // 提供 Next.js 應用程式的路徑,以便在測試環境中載入 next.config.js 和 .env 檔案
  dir: './',
})

// 新增任何要傳遞給 Jest 的自訂配置
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // 在每個測試執行前新增更多設定選項
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}

// 以這種方式匯出 createJestConfig,以確保 next/jest 能載入非同步的 Next.js 配置
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 or 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 配置檔中新增以下選項,為每個測試匯入這些自訂匹配器:

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

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

import '@testing-library/jest-dom'

須知事項:extend-expect 已在 v6.0 中移除,因此如果你使用的是 @testing-library/jest-dom 6.0 之前的版本,則需要匯入 @testing-library/jest-dom/extend-expect 替代。

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

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 /> 元件是否成功渲染了一個標題:

import Link from 'next/link'

export default function Home() {
  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()
})

執行你的測試

然後,執行以下指令來執行你的測試:

Terminal
npm run test
# 或
yarn test
# 或
pnpm test

其他資源

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

On this page