I want to write tests for the following function using Vitest.
import { randomUUID } from "node:crypto";
export const getRandomUUID = (): string => {
return randomUUID();
}
I wrote the following test code for the above function.
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRandomUUID } from "./utils";
vi.mock("node:crypto", () => {
return {
randomUUID: vi.fn(() => "mock-uuid"),
};
});
describe("getRandomUUID", () => {
it("mock-uuid", () => {
const uuid = getRandomUUID();
expect(uuid).toBe("mock-uuid");
});
});
Then, the following error occurred.
Error: [vitest] No "default" export is defined on the "node:crypto" mock. Did you forget to return it from "vi.mock"? If you need to partially mock a module, you can use "importOriginal" helper inside:
Therefore, I rewrote the mock part as follows.
vi.mock("node:crypto", async () => {
const actual = await vi.importActual<typeof import("node:crypto")>("node:crypto");
return {
...actual,
randomUUID: vi.fn(() => "mock-uuid"),
};
});
Then, the following error occurred.
AssertionError: expected '5cedbc46-aaaf-40f3-9943-fbaedb9da36b' to be 'mock-uuid' // Object.is equality
I believe this is an AssertionError caused by not properly mocking randomUUID, but I am unsure how to resolve it and would like your guidance.