0
votes

I am trying to mock a server in some UI tests that I am writing using cypress. I am probably making some basic mistake and might not be understanding how cypress is stubbing requests. Here is an example app that I copied straight from expressjs -

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello from /'));
app.get('/user', (req, res) => res.send('Hello from /user'));

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

And then wrote a simple test using cypress -


describe('Stubbed request', () => {
  it('sends whatever response you want', () => {
    cy.visit('http://localhost:3000/');
    cy.server();
    cy.route({
      method: 'GET',
      url: '/user',
      response: [],
    }).as('bar');

    cy.visit('http://localhost:3000/user'); // cy.request() has same behavior
    cy.wait('@bar');
  })
})

I was hoping that instead of 'Hello from user/', I should get an empty response since I have stubbed it with cypress. Even cy.wait fails with message - "CypressError: Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: 'bar'. No request ever occurred." I am obviously doing something wrong. Can someone please help me understand what am I doing wrong? Thanks in advance.

1

1 Answers

0
votes

You can only stub/spy XHR requests that are created within your app. cy.visit will never make such a xhr request. neither you can stub a request made with cy.request because thise requests are intended to work indepentent from all active network stubs. This means, you are able to stub /users but in your test you can make a real request to that route by using cy.request.

In your case, you must deliver a static html site with express that e.g. contains a button. And after the button is clicked, you can execute e.g. $.get(' /user'). Then this request will be stubbed.

Currently I am not at home so I can not provide a runnable example. But with the hints above you should be able to do this. Let me know if you need further assistance.

Also you can take a look at cypress XHR API call validation in test cases . Here I have provided a runnable example fir stubbing and spying.