For example, how can I mock the hello
function and .mockReturnValue("Hi")
? Hoping someone can assist with this simple example as it's quite confusing to me currently.
// greet.ts
export function hello() {
return "Hello ";
}
export function greet(name: string) {
return hello() + name;
}
Test file:
// greet.spec.ts
import {hello, greet} from "./greet";
vi.mock("./greet", async () => {
const mod = await vi.importActual<typeof
import("./greet")>("./greet");
const hello = vi.fn().mockReturnValue("Hi ");
return {
...mod,
hello,
// greet: vi.fn((name: string)=> hello() + name),
// ^this works if I uncomment it, but it defeats
// the purpose of the test.
// Is it just not possible to do what I want?
}
})
describe("Greeting", () => {
test("should return a personalized greeting", async () => {
const result = greet("John");
expect(result).toBe("Hi John");
expect(hello).toHaveBeenCalled();
});
});
Running the test still gives Hello John
and the hello
function is not called. No surprise... how can I mock the implementation of hello()
in the actual greet
function?