Skip to content

Instantly share code, notes, and snippets.

@zaru
Last active June 14, 2024 01:39
Show Gist options
  • Save zaru/273d466f896c84d7cc0f6a5f6494c2e6 to your computer and use it in GitHub Desktop.
Save zaru/273d466f896c84d7cc0f6a5f6494c2e6 to your computer and use it in GitHub Desktop.
Bun test / VitestでNext.jsのServer Actionsをテストする
import { describe, expect, mock, test } from "bun:test";
import { sampleAction } from "@/app/sampleAction";
describe("sampleAction", () => {
test("正常:返り値が正しく返ってくる", async () => {
const result = await sampleAction(true);
expect(result).toEqual({ sampleAction: "sampleAction" });
});
test("異常:エラーページにリダイレクトされる", async () => {
mock.module("next/navigation", () => {
return {
redirect: (path: string) => {
return path;
},
};
});
const result = await sampleAction(false);
// @ts-ignore redirectの返り値がunknownなので型エラーになってしまう。Bunでモジュールモックの呼び出し回数チェックできないのでこれで回避。
expect(result).toBe("/error");
});
});
"use server";
import { redirect } from "next/navigation";
export async function sampleAction(flag = false) {
if (flag) {
return { sampleAction: "sampleAction" };
}
return redirect("/error");
}
import { afterEach, describe, expect, test, vi } from "vitest";
import { sampleAction } from "./sampleAction";
describe("sampleAction", () => {
test("正常:返り値が正しく返ってくる", async () => {
const result = await sampleAction(true);
expect(result).toEqual({ sampleAction: "sampleAction" });
});
test("異常:エラーページにリダイレクトされる", async () => {
vi.mock("next/navigation", () => {
return {
redirect: (path: string) => {
return path;
},
};
});
const result = await sampleAction(false);
expect(result).toBe("/error");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment