I would like to test the following code:
// DocRepo.ts
export class DocRepo {
constructor() {}
async fetchDocs(id: String) {
return Promise.resolve([])
}
}
// Person.ts
import {DocRepo} from "./DocRepo";
export default class Person {
let docRepo;
constructor() {
docRepo = new DocRepo();
}
async findDocs(){
return docRepo.fetchDocs()
}
}
I came up with the following test cases:
import Person from "./Person";
import { DocRepo } from "./DocRepo";
jest.mock("./DocRepo");
describe("Person", () => {
it("should fetch documents", async () => {
const mockFetchDocs = jest.fn().mockResolvedValue([]);
DocRepo.prototype.fetchDocs = mockFetchDocs; // bad practice?
const person = new Person();
await person.findDocs();
expect(mockFetchDocs).toHaveBeenCalledTimes(1);
});
});
Is it bad practice to override the function prototype like DocRepo.prototype.fetchDocs = mockFetchDocs
? If yes, please suggest the correct way to test this code ( WITHOUT changing the constructors).