😄

Jestとmswのテスト環境セットアップのメモ

2024/06/18に公開

Jestとmswのテスト環境セットアップのメモ

以下の公式サイトにあるJestのセットアップを完了していることを前提条件にする
pagesルーター
Setting up Jest with Next.js

mswの設定

src/mocksのようにフォルダ内にファイル作成

handler.ts
import { HttpResponse, http } from "msw";

export const handlers = [
  // jestでenvironmentがnodeの場合、絶対パスで指定していないとエラーが出る↓
  // "TypeError: Only absolute URLs are supported"
  // 動作環境がnodeの場合、URLはhttp://localhost:3000/api/articles

  http.get("/api/user", () => { 
    return HttpResponse.json({
      username: 'user1',
    });
  })
];
browser.ts
import { setupWorker } from "msw/browser";
import { handlers } from "./handler";

export const worker = setupWorker(...handlers);
server.ts
import { setupServer } from "msw/node"
import { handlers } from "./handler"

export const server = setupServer(...handlers);
index.ts
// 各環境下に合うワーカーを実行
async function init() {
  if (typeof window === 'undefined') {
    const { server } = await import('./server')
    server.listen()
  } else {
    const { worker } = await import('./browser')
    worker.start()
  }
}

init()

export {}
App.tsx
import "@/styles/globals.css";

import type { AppProps } from "next/app";

// NODE_ENV指定で開発環境時でしか動作しないようにしている
if(process.env.NODE_ENV === "development") {
  require('../mocks')
}

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
    </>
  );
}

公開ディレクトリの指定
プロジェクトディレクトリの一番上の階層で行う

npx msw init public --save public/

jestの設定

jestもしくはテスト用のフォルダを作成する。その中にjestの設定ファイルの作成

jest.setup.ts
import { server } from "@/mocks/server";
import _fetch from "node-fetch";

// @ts-ignore
global.fetch = _fetch;

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

以下をコメントアウトを外し、入力

jest.config.ts
const config:Config = {
  setupFilesAfterEnv: ['<rootDir>/ディレクトリ名/jest.setup.ts'],
  testEnvironment: "node",
  // Cannot find module 'msw/node' fromというエラーが発生していたら以下を追加
  testEnvironmentOptions: {
    customExportConditions: [''],
  },
}

以下はお好みで

fetcher.ts
export const fetcher = async ({ url, method = 'GET', reqBody }) => {
  const response = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(reqBody),
  });

  return response.json();
};

テストファイル作成

example.test.ts
describe("example", () => {
  it("fetch", async() => {
    const expectedValue = { username: 'user1' };

    const response = await fetcher({ url: `http://localhost:3000/api/user` });

    expect(response).toEqual(expectedValue);
  });
});

こんな感じにテストが通ったら完了

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.828 s
GitHubで編集を提案

Discussion