Fixtures and Network Stubbing with cy.intercept
On this page
Because Cypress sits between your application and the network, it can watch every HTTP request the page makes, wait for it, check what was sent and, when you want, answer it with data you control. This chapter covers cy.intercept(), fixture files and cy.request(), using the network demo page at example.cypress.io/commands/network-requests. Its "Get Comment" button fetches https://jsonplaceholder.cypress.io/comments/1 and shows the comment body on the page.
Fixture files#
A fixture is a file of test data in cypress/fixtures/. Create cypress/fixtures/comment.json:
{
"id": 1,
"name": "stubbed comment",
"email": "learner@example.com",
"body": "This came from cypress/fixtures/comment.json"
}
You can load it into a test with cy.fixture():
it('loads a fixture as test data', () => {
cy.fixture('comment.json').then((comment) => {
cy.visit('/todo')
cy.get('[data-test=new-todo]').type(`${comment.name}{enter}`)
cy.contains('.todo-list li', comment.name).should('exist')
})
})
Fixtures are most useful as stubbed responses, which is next.
Spying: wait for a real request#
Create cypress/e2e/network.cy.js. The first test lets the request go to the real server but spies on it:
describe('network requests', () => {
beforeEach(() => {
cy.visit('/commands/network-requests')
})
it('waits for the real request', () => {
cy.intercept('GET', '**/comments/*').as('getComment')
cy.get('.network-btn').click()
cy.wait('@getComment').its('response.statusCode').should('eq', 200)
cy.get('.network-comment').should('not.be.empty')
})
})
-
cy.intercept(method, url)registers a route.**/comments/*is a glob: any host, any comment id. -
.as('getComment')names it, andcy.wait('@getComment')waits until a matching request has completed, then yields an object withrequestandresponse. - Register the intercept before the action that triggers the request. An intercept set up after the click never sees a request that has already gone out.
This is the replacement for cy.wait(2000) from chapter 3 when what you are really waiting for is the server.
A test clicks "Save" and then calls cy.intercept('POST', '/api/items').as('save') followed by cy.wait('@save'). It times out even though the request clearly happens. Why?
Commands run in order, so the route only exists from the moment cy.intercept runs. Register it first, then do the action, then wait on the alias.
Stubbing: answer with your own data#
Pass a third argument and the request never reaches the server; Cypress answers it:
it('stubs the response with a fixture', () => {
cy.intercept('GET', '**/comments/*', { fixture: 'comment.json' }).as('getComment')
cy.get('.network-btn').click()
cy.wait('@getComment')
cy.get('.network-comment').should('have.text', 'This came from cypress/fixtures/comment.json')
})
Stubbing gives you fast, deterministic tests for things that are hard to set up on a real backend: an empty list, a very long one, a 500 error, a slow response. The error path is a good example, because few teams ever test it otherwise:
it('shows the error path when the server fails', () => {
cy.intercept('PUT', '**/comments/*', {
statusCode: 404,
body: { error: 'comment not found' },
}).as('putComment')
cy.get('.network-put').click()
cy.wait('@putComment')
cy.get('.network-put-comment').should('contain', 'comment not found')
})
The page calls a different origin (jsonplaceholder.cypress.io), yet the stub needs no CORS headers: for a static response Cypress adds access-control-allow-origin (set to the page's origin) and access-control-allow-credentials itself, so the browser accepts it. That only applies to responses Cypress answers. A CORS error on a request that reaches the real server is a real bug, and the fix belongs on the server. Add delay: 3000 to the same object to simulate a slow server, as chapter 3 did.
Your whole suite stubs every API call with fixtures. It is fast and green, but production broke when the backend renamed a JSON field. What does that tell you?
A stub returns whatever you wrote, so it cannot notice the real API changing. Stub to test UI states that are hard to reach, and keep a smaller set of end-to-end tests that go through the real backend (spying with cy.intercept still lets you wait on those).
Checking what the app sent#
cy.wait yields the intercepted request, so you can assert on the payload as well as the response:
it('checks what the app sent', () => {
cy.intercept('POST', '**/comments').as('postComment')
cy.get('.network-post').click()
cy.wait('@postComment').then(({ request, response }) => {
expect(request.body).to.include('email')
expect(response.statusCode).to.eq(201)
})
cy.get('.network-post-comment').should('contain', 'POST successful!')
})
This page sends form-encoded data, so request.body is a string; for a JSON API it is an object and you can use to.have.property('email').
Changing part of a real response#
Between "let it through" and "answer it yourself" there is a third option: pass a function, let the request reach the server, and edit the response on its way back:
it('changes part of a real response', () => {
cy.intercept('GET', '**/comments/*', (req) => {
req.continue((res) => {
res.body.body = 'edited on the way back'
})
}).as('getComment')
cy.visit('/commands/network-requests')
cy.get('.network-btn').click()
cy.wait('@getComment').its('response.body.id').should('eq', 1)
cy.get('.network-comment').should('have.text', 'edited on the way back')
})
This keeps the real contract (status, headers, the other fields) while forcing the one value you care about, for example a feature flag or a date.
cy.request: talk to the API without the page#
cy.intercept deals with requests the page makes. cy.request makes a request from the test itself, outside the browser page, and is not subject to CORS:
it('calls an API directly with cy.request', () => {
cy.request('https://jsonplaceholder.cypress.io/comments/1').then((res) => {
expect(res.status).to.eq(200)
expect(res.body).to.have.property('email')
})
})
Use it to seed data before a test, clean up after one, or log in without the UI. That last use is the subject of the next chapter.
Before each test you need three todo items to exist on the server. Which approach is the most reliable?
Setting up data through the API is fast and does not depend on the UI you are about to test. Typing through the form is slow and tests the form again in every test; relying on an earlier test breaks as soon as tests run alone or in a different order.