Assume I have 2 modules that defines Repo
and Service
classes.
// src/Repo.ts
export class Repo {
find() {
return "hello";
}
}
// src/Service.ts
import { Repo } from "./Repo";
export class Service {
private repo = new Repo();
find() {
return this.repo.find();
}
}
I these classes the important thing is we are not passing Repo
instance to the constructor of Service
rather they are initialized inline.
Following is the test I’ve written and I would like to update the mockReturnValue
within the test so that I can have different values suitable for each test. Following doesn’t work and find()
returns undefined
but something like this even possible in Vitest? (As far as I remember, something like this is possible in Jest)
import { Service } from "../../src/Service.ts";
import { Repo } from "../../src/Repo.ts";
import { describe, expect, it, vi } from "vitest";
vi.mock("../../src/Repo.ts", () => ({
Repo: vi.fn().mockImplementation(() => {
return {
find: vi.fn(),
};
}),
}));
describe("sample", () => {
it("test something", () => {
const repo = new Repo();
repo.find.mockReturnValue("world");
const service = new Service();
console.log(service.find());
expect(service.find()).toBe("world");
});
});