Example result: Mock an external API in your tests
AI-generated example · Test Mocks
Updated

Mock an external API in your tests

This prompt shows how to test code that calls an outside service, such as a payments API, without hitting the real thing. It covers success, errors, timeouts and bad data, and explains the gap mocks leave.

text-code-mock-external-api — claude — 84 words

Act as a senior [LANGUAGE] developer.

My code calls this external service: [e.g. Razorpay payments API]
Code that makes the call:
[PASTE]
Test framework: [e.g. Jest / pytest]

Show me how to test this code without calling the real service. Mock the success case, an error response, a timeout and a malformed response. Keep the mock at the network or client boundary, not deep inside my code. Explain what the mocks can miss and suggest one contract or sandbox test to cover that gap.

Mocks prove your code handles responses. They cannot prove the real API still behaves the same, so keep one real check somewhere.

Get a better result

What you will get

Test code that fakes the outside service at the client boundary, covering a success, an error response, a timeout and a malformed reply, plus a note on what mocks cannot catch.

Common mistake

The mock lives deep inside your own code.

Fix: Ask it to wrap the HTTP client in one small function and fake that, so your real logic still runs in the test.

Also watch for
  • The mocked reply is made up. Paste a real sample response from the provider’s documentation and say “use this shape exactly”.
  • Timeouts are never tested. Ask for a test that waits past your limit and checks the retry or fallback behaviour, not just the happy path.
Try a variation: record real replies

Ask how to record one real response once, store it as a fixture file, and replay it in tests instead of hand-written mocks.

Still not right? Reply with this

Write one contract or sandbox test that calls the real provider, and show how to run it on a schedule so a change on their side shows up quickly.

Guides on this topic

More chat & writing prompts

See all 465 →