Types के साथ Mocking
In this page:
const mockFn = jest.fn<returnType, [paramType]>();
mockFn.mockReturnValue(value);
jest.mock("./module");
एक Function Mock करना
jest.fn<ReturnType, Args>() से एक single function mock करना original function की call signature preserve करता है, इसलिए mock को गलत argument types से call करना type checker द्वारा flag किया जाता है exactly उसी तरह जैसे असली function को call करना होता।
उदाहरण: Mocking a Function
type Add = (a: number, b: number) => number;
const mockAdd: Add = (a, b) => a + b;
console.log(mockAdd(2, 3));
Object Dependencies Mock करना
एक object dependency (जैसे एक service class) mock करने का मतलब है एक fake object देना जो उसी interface को satisfy करे, इसलिए TypeScript verify करता है कि mock असल में वह हर method implement करता है जो असली dependency expose करती है।
उदाहरण: Mocking Object Dependencies
interface Logger {
log(msg: string): void;
}
const mockLogger: Logger = { log: (msg) => console.log("MOCK:", msg) };
mockLogger.log("test message");
Calls Record करना
एक typed mock पर calls record करना — mock.calls के through — आपके pass किए argument types preserve करता है, इसलिए expect(mockFn.mock.calls[0][0]).toBe(...) assert करना any resolve होने के बजाय type-safe रहता है।
उदाहरण: Recording Calls
const calls: [string][] = [];
function mockLog(msg: string) {
calls.push([msg]);
}
mockLog("hello");
console.log(calls[0][0]);
Partial Mocks
एक partial mock सिर्फ test से relevant methods replace करता है जबकि असली object का बाकी हिस्सा intact छोड़ता है, Partial<T> से typed इसलिए compiler track करता है कि genuinely कौन से parts mocked हैं versus असली।
उदाहरण: Partial Mocks
interface Config {
apiUrl: string;
timeout: number;
}
const partialMock: Partial<Config> = { apiUrl: "http://test" };
console.log(partialMock);
Async Dependencies Mock करना
एक async dependency mock करने का मतलब है mock function को असली method के resolved type से match करने वाला एक Promise return करना चाहिए, इसलिए mockResolvedValue(...) असली async signature के against type-checked होता है।
उदाहरण: Mocking Async Dependencies
interface Api {
fetchUser(): Promise<string>;
}
const mockApi: Api = { fetchUser: () => Promise.resolve("mocked-user") };
mockApi.fetchUser().then(console.log);
- एक mock को
anyके रूप में type करना, इसलिए test अब यह check नहीं करता कि mock असली interface से match करता है। - Tests के बीच mocks reset या clear करना भूल जाना, इसलिए call counts एक test से दूसरे में leak होते हैं।
- एक object का सिर्फ कुछ हिस्सा mock करना और इसे
as Serviceसे cast करना, जो missing methods hide करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: