Cypress · Browser testing end to end
How do you use cy.intercept with request and response handlers?
Short answer
Pass a method and URL matcher plus a handler. The handler receives req and can call req.reply to stub, req.continue to forward, or req.on to modify the response before it reaches the app.
cy.intercept has two handler styles. A static object is a quick stub. A function handler gives you the request object, where you can inspect headers, query parameters and body, decide whether to continue to the server, and modify the response on its way back.
cy.intercept("POST", "/api/orders", (req) => {
expect(req.body).to.have.property("items");
req.reply((res) => {
res.body.status = "accepted";
res.headers["x-test"] = "true";
});
}).as("createOrder");
cy.get("[data-cy=place-order]").click();
cy.wait("@createOrder").its("response.statusCode").should("eq", 201);Matchers and handlers
- Use a string, glob or RegExp to match the URL
- Use a fixture option for a static response
- Use req.reply(body) to stub without calling the server
- Use req.continue() to forward the request, optionally modifying it
- Use req.on with a response event to observe or alter the real response
- Use a route matcher function for complex matching, such as request body fields
The request body is only available once Cypress has parsed it. For a POST, the body is usually an object; for some content types it may be a string. Do not assume a shape without checking the request, and avoid mutating a request in a way that changes the behaviour under test.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between req.reply and req.continue?
- 2How do you modify a real response without stubbing it?
- 3How do you match on a request body?
- 4What does cy.wait on an intercept yield?
Say it in the interview
cy.intercept takes a matcher and a handler. If I pass a function, I get the request and can assert on it, stub with req.reply, or continue to the server with req.continue. I can also attach a reply callback to edit the real response. I alias the route so the test can wait for the exact request and then assert on the interception it yields.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Cypress mock interview and get scored feedback on depth, clarity and confidence.