0

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.

1
  • When you use vi.importActual to preserve the real implementation of node:crypto and add a mock for randomUUID, the mock might not be properly overriding the actual randomUUID in the environment where your test runs. Mock node:crypto completely so that randomUUID is replaced everywhere it is used. Commented Dec 17, 2024 at 13:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.