如何在 Next.js 中設定 Jest

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

須知事項: 由於 async 伺服器元件 (Server Components) 對 React 生態系統來說是新功能,Jest 目前不支援它們。雖然您仍然可以對同步的伺服器元件和客戶端元件 (Client Components) 進行單元測試,但我們建議對 async 元件使用端到端測試 (E2E tests)

快速開始

您可以使用 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
# 或
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# 或
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
# 或
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 編譯器 (Next.js Compiler) 設定 transform
  • 自動模擬樣式表 (.css, .module.css 及其 scss 變體)、圖片匯入和 next/font
  • .env (及其所有變體) 載入到 process.env
  • 忽略 node_modules 不進行測試解析和轉換
  • 忽略 .next 不進行測試解析
  • 載入 next.config.js 以啟用 SWC 轉換的標誌

須知事項:要直接測試環境變數,請在單獨的設定腳本或 jest.config.ts 檔案中手動載入它們。更多資訊請參閱測試環境變數 (Test Environment Variables)

設定 Jest (搭配 Babel)

如果您選擇不使用 Next.js 編譯器 (Next.js Compiler) 而改用 Babel,您需要手動配置 Jest 並安裝 babel-jestidentity-obj-proxy,以及上述套件。

以下是為 Next.js 配置 Jest 的推薦選項:

jest.config.js
module.exports = {
  collectCoverage: true,
  // 在 node 14.x 上,coverage provider v8 提供良好的速度和大致良好的報告
  coverageProvider: 'v8',
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
    '!<rootDir>/out/**',
    '!<rootDir>/.next/**',
    '!<rootDir>/*.config.js',
    '!<rootDir>/coverage/**',
  ],
  moduleNameMapper: {
    // 處理 CSS 匯入 (搭配 CSS 模組)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // 處理 CSS 匯入 (不搭配 CSS 模組)
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',

    // 處理圖片匯入
    // https://jestjs.io/docs/webpack#handling-static-assets
    '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,

    // 處理模組別名
    '^@/components/(.*)$': '<rootDir>/components/$1',

    // 處理 @next/font
    '@next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
    // 處理 next/font
    'next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
    // 停用 server-only
    'server-only': `<rootDir>/__mocks__/empty.js`,
  },
  // 在每個測試執行前新增更多設定選項
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'jsdom',
  transform: {
    // 使用 babel-jest 搭配 next/babel 預設來轉譯測試
    // https://jestjs.io/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.jsstyleMock.js

__mocks__/fileMock.js
module.exports = 'test-file-stub'
__mocks__/styleMock.js
module.exports = {}

有關處理靜態資源的更多資訊,請參閱 Jest 文件

處理字型

要處理字型,請在 __mocks__ 目錄中建立 nextFontMock.js 檔案,並新增以下配置:

__mocks__/nextFontMock.js
module.exports = new Proxy(
  {},
  {
    get: function getter() {
      return () => ({
        className: 'className',
        variable: 'variable',
        style: { fontFamily: 'fontFamily' },
      })
    },
  }
)

可選:處理絕對匯入和模組路徑別名

如果您的專案使用模組路徑別名 (Module Path Aliases),您需要配置 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 包含一組方便的自定義匹配器 (custom matchers),例如 .toBeInTheDocument(),使撰寫測試更容易。您可以透過在 Jest 配置檔中新增以下選項來為每個測試匯入這些自定義匹配器:

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

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

import '@testing-library/jest-dom'

須知事項: extend-expectv6.0 中被移除,因此如果您使用的是 @testing-library/jest-dom 6.0 之前的版本,您需要改為匯入 @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__ 的資料夾。

例如,我們可以新增一個測試來檢查 <Home /> 元件是否成功渲染了一個標題:

export default function Home() {
  return <h1>Home</h1>
}
__tests__/index.test.js
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()
  })
})

可選地,新增一個快照測試 (snapshot test) 來追蹤元件中的任何意外變更:

__tests__/snapshot.js
import { render } from '@testing-library/react'
import Home from '../pages/index'

it('renders homepage unchanged', () => {
  const { container } = render(<Home />)
  expect(container).toMatchSnapshot()
})

須知事項:測試檔案不應包含在頁面路由器 (Pages Router) 中,因為頁面路由器中的任何檔案都會被視為路由。

執行您的測試

然後,執行以下命令來執行您的測試:

終端機
npm run test
# 或
yarn test
# 或
pnpm test

其他資源

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

On this page