Lesson 12 / 25
Stubbing and Waiting with cy.intercept
Spy, stub and wait on network calls.
Spying and stubbing requests
cy.intercept(method, url, response?) registers a route for requests made by the application. Without a response it spies: the request goes through and you can inspect it. With a static response such as { fixture: 'todos.json' }, { statusCode: 500 } or a body object it stubs. A handler function can modify the request (req.reply, req.continue(res => ...)). Give the route an alias with .as('getTodos') and use cy.wait('@getTodos') to wait until that call happens, then assert on the request or response. Register intercepts before the action (often before cy.visit) that triggers the request.
Stub, wait and assert on a request
Fixture stub and a spied POST.
it('adds a todo and sends it to the API', () => {
cy.intercept('GET', '/api/todos', { fixture: 'todos.json' }).as('getTodos');
cy.intercept('POST', '/api/todos').as('createTodo'); // spy only
cy.visit('/todos');
cy.wait('@getTodos');
cy.get('[data-cy=new-todo]').type('Buy milk{enter}');
cy.wait('@createTodo').then(({ request, response }) => {
expect(request.body).to.include({ title: 'Buy milk' });
expect(response?.statusCode).to.eq(201);
});
});
it('shows an error banner on server failure', () => {
cy.intercept('GET', '/api/todos', { statusCode: 500 }).as('getTodos');
cy.visit('/todos');
cy.wait('@getTodos');
cy.contains('[role=alert]', 'Could not load').should('be.visible');
});Wait on aliases, not on time
cy.wait('@alias') waits exactly as long as the request takes. cy.wait(2000) is either too long (slow suite) or too short (flaky suite).
A switchboard operator
cy.intercept is an operator on the line between app and server: they can just listen, answer the call themselves, or pass it on with a changed message.
Quick check: What does `cy.wait('@getTodos')` do?
- Pauses for a fixed number of milliseconds
- Waits until the aliased intercepted request has happened
- Reloads the page until todos appear
- Creates a new fixture file
Answer
Waits until the aliased intercepted request has happened — Alias-based waits are deterministic.