← Back to TypeScript Course | Chapter 24: Testing TypeScript | Lesson 4 of 6

Types के साथ Mocking

Mocks असली dependencies को controlled test implementations से replace करते हैं। TypeScript mock objects और functions describe कर सकता है इसलिए tests production API के साथ aligned रहते हैं।
Syntax
typescript
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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
interface Api {
  fetchUser(): Promise<string>;
}
const mockApi: Api = { fetchUser: () => Promise.resolve("mocked-user") };
mockApi.fetchUser().then(console.log);
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक mock को any के रूप में type करना, इसलिए test अब यह check नहीं करता कि mock असली interface से match करता है।
  2. Tests के बीच mocks reset या clear करना भूल जाना, इसलिए call counts एक test से दूसरे में leak होते हैं।
  3. एक object का सिर्फ कुछ हिस्सा mock करना और इसे as Service से cast करना, जो missing methods hide करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.