Tests में API Calls को Mock करना
In this page:
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 बनाते हुए।
उदाहरण: Why Mock API Calls in Tests
// 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 करता है।
उदाहरण: Creating a Mock Function with jest.fn()
// 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 रखता है।
उदाहरण: Resetting Mocks Between Tests
// 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
});
- Tests में real network requests बनाना, जो slow, flaky हैं, और एक external service के up होने पर depend करते हैं।
- Tests के बीच mocks reset या restore करना भूल जाना, एक test के mock को दूसरे में leak होने देते हुए।
- 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 में नहीं।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: