I tried following another related post on this topic with the creator’s same outcome.
Since its post is dead I’d like to try again if someone has an idea on how to mock the node:crypto
function or any builtin function.
My base case study is a simple randomUUID generator just to test that the mocking is working so:
import { randomUUID } from "node:crypto";
export function getRandomUUID() :string {
return randomUUID();
}
and I tried like in the above post the suggested solution:
vi.mock("node:crypto", async () => {
const actual =
await vi.importActual<typeof import("node:crypto")>("node:crypto");
return {
...actual,
randomUUID: vi.fn(() => "123456789"),
};
});
The getRandomUUID return undefined in this case
I also tried a similar jest solution on this post
but vitest fails with an error about the import:
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:
vi.mock(import("node:crypto"), async (importOriginal) => {
const actual = await importOriginal()
return {
...actual,
// your mocked methods
}
})
so I tried this one as well with my mock method (the mock doesn’t like the return type of randomUUID tho Type 'string' is not assignable to type '
${string}-${string}-${string}-${string}-${string}'
)
vi.mock(import("node:crypto"), async (importOriginal) => {
const actual = await importOriginal();
return {
actual,
// your mocked methods
randomUUID: vi.fn(() => "123456789"),
};
});
and doesn’t mock the actual method