Last active
June 14, 2024 01:39
-
-
Save zaru/273d466f896c84d7cc0f6a5f6494c2e6 to your computer and use it in GitHub Desktop.
Bun test / VitestでNext.jsのServer Actionsをテストする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use server"; | |
import { redirect } from "next/navigation"; | |
export async function sampleAction(flag = false) { | |
if (flag) { | |
return { sampleAction: "sampleAction" }; | |
} | |
return redirect("/error"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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