跳至內容

使用 Next.js 設定 Jest (Setting up Jest with Next.js)

Jest 和 React 測試函式庫經常搭配使用,用於單元測試快照測試。本指南將向您展示如何使用 Next.js 設定 Jest 並編寫您的第一個測試。

貼心小提醒:由於 async 伺服器元件對於 React 生態系統來說還很新,Jest 目前還不支援它們。雖然您仍然可以針對同步的伺服器和客戶端元件運行單元測試,但我們建議對 async 元件使用端對端測試 (E2E 測試)

快速入門

您可以使用 Next.js 的 with-jest 範例搭配 create-next-app 來快速上手。

終端機
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
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node

透過執行以下指令來產生基本的 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(使用 Babel)

如果您選擇不使用 Next.js 編譯器 而改用 Babel,除了上述套件之外,您還需要手動設定 Jest 並安裝 babel-jestidentity-obj-proxy

以下是為 Next.js 設定 Jest 的建議選項:

jest.config.js
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.dev.org.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.dev.org.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.dev.org.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.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' },
      })
    },
  }
)

選用:處理絕對導入和模組路徑別名

如果您的專案正在使用模組路徑別名,您需要設定 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.ts 檔案內,加入以下 import 陳述式

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

注意事項:extend-expect 已於 v6.0 中移除,因此如果您使用的是 @testing-library/jest-dom 6 以前的版本,則需要改為導入 @testing-library/jest-dom/extend-expect

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

將測試腳本加入到 package.json 中:

最後,將 Jest test 腳本加入到您的 package.json 檔案中

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()
  })
})

(選用)加入快照測試以追蹤元件中任何非預期的變更

__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 資料夾內,因為 Pages Router 中的任何檔案都會被視為路由。

執行測試

接著,執行以下指令來運行您的測試

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

其他資源

如需進一步了解,以下資源可能對您有所幫助