← Back to React Course | Chapter 12: Testing React Applications | Lesson 6 of 9

Tests में API Calls को Mock करना

एक test में API call mock करना ऐसा है जैसे real actor के बजाय एक stunt double उपयोग करना — यह उस part जैसा दिखता और करता है, लेकिन असली, risky चीज़ को actually होने की ज़रूरत नहीं।
Syntax
markup
const mockFn = jest.fn();
mockFn.mockResolvedValue(fakeData);
global.fetch = jest.fn(() =>
  Promise.resolve({ json: () => Promise.resolve(fakeData) })
);

afterEach(() => jest.resetAllMocks());

Tests में API Calls क्यों Mock करें

Tests में real network requests बनाना slow है, एक external service के actually available होने पर depend करता है, और हर run में अलग results produce कर सकता है।

Mocking real request को एक fake, predictable response से replace करता है, tests को fast, reliable, और किसी real backend से independent बनाते हुए।

Note: Mocked responses को real API के shape से closely match करना चाहिए, ताकि आपके tests meaningful रहें अगर mock कभी reality से drift हो।
Warning: Over-mocking real integration bugs को hide कर सकता है — mocked APIs वाले unit tests को एक छोटी संख्या में real integration/E2E tests के साथ pair करें।

उदाहरण: Why Mock API Calls in Tests

markup
// Run in your local React project (npm install required)
test('fetches and displays user', async () => {
  global.fetch = jest.fn(() =>
    Promise.resolve({ json: () => Promise.resolve({ name: 'Asha' }) })
  );
  render(<UserProfile userId={1} />);
  expect(await screen.findByText('Asha')).toBeInTheDocument();
});

jest.fn() से एक Mock Function बनाना

jest.fn() एक special mock function बनाता है जो record करता है कि यह कैसे call हुआ (arguments, call count) और आपको control करने देता है यह क्या return करता है, कोई real logic run किए बिना। यह सिर्फ fetch mock करने के लिए नहीं, किसी भी function के लिए useful है जिस पर एक component depend करता है।

Note: mockFn.mockReturnValue(...) या mockResolvedValue(...) उपयोग करें control करने के लिए कि call होने पर mock function क्या return करता है।
Warning: एक mock function default रूप से कुछ नहीं करता (undefined return करता है) जब तक आप explicitly एक return value configure न करें।

उदाहरण: Creating a Mock Function with jest.fn()

markup
// Run in your local React project (npm install required)
const mockOnSave = jest.fn();

test('calls onSave when button clicked', async () => {
  const user = userEvent.setup();
  render(<SaveButton onSave={mockOnSave} />);
  await user.click(screen.getByText('Save'));
  expect(mockOnSave).toHaveBeenCalledTimes(1);
});

Tests के बीच Mocks Reset करना

Mock functions और mocked globals (जैसे fetch) tests के बीच state (जैसे call counts) retain कर सकते हैं अगर reset न किया जाए, जिससे एक test का setup accidentally दूसरे को affect कर सकता है।

afterEach में jest.clearAllMocks() call करना या original implementation restore करना हर test को properly isolated रखता है।

Note: एक common setup pattern है एक global afterEach में jest.clearAllMocks() call करना, ताकि हर test automatically एक clean slate से शुरू हो।
Warning: Tests के बीच cleanup skip करना confusing, hard-to-diagnose failures का कारण बन सकता है जहां एक test pass या fail होता है depending on पहले क्या run हुआ।

उदाहरण: Resetting Mocks Between Tests

markup
// Run in your local React project (npm install required)
afterEach(() => {
  jest.clearAllMocks();
  delete global.fetch;
});

test('example test', () => {
  global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}) }));
  // ... test body
});
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. Tests में real network requests बनाना, जो slow, flaky हैं, और एक external service के up होने पर depend करते हैं।
  2. Tests के बीच mocks reset या restore करना भूल जाना, एक test के mock को दूसरे में leak होने देते हुए।
  3. fetch के response shape को incorrectly mock करना, जो real API actually return करता है उससे match न करते हुए।
चैप्टर सारांश
  • Mocking testing purposes के लिए एक real API call को एक fake, predictable वाले से replace करता है।
  • jest.fn() एक mock function बनाता है जिसे आप एक test के अंदर control और inspect कर सकते हैं।
  • Global fetch directly mock किया जा सकता है, या msw जैसी एक library requests को ज़्यादा realistically intercept कर सकती है।
  • Tests के बीच mocks reset करना (afterEach) एक test के setup को दूसरे में leak होने से बचाता है।
ब्राउज़र सपोर्ट

npm install (Jest/Vitest) चाहिए — mocking Node test environment में run होता है, इस browser sandbox में नहीं।

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.