Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock network requests in Cypress

I've been tearing my hair out over this for ages now - and I hope someone can help me :)

I've been trying to stub a network request in Cypress for ages now.

commands.js

Cypress.Commands.add('login', (
    email = 'email',
    password = 'pass'
) => {
    cy.server();
    cy.visit('url');
    cy.get('input[name="username"').type(email);
    cy.get('form').submit();
    cy.get('input[name="password"').type(password);
    cy.get('form').submit();
});

mock.js

describe('mock', function() {
    it('user can login', function() {
        cy.login();
        cy.get('main[role="main"]');

        cy.route('GET',
            '**/getIncentives*',
            {info: {}, results: {}}
        ).as('oppty');

        cy.wait('@oppty');
    });
});

Chrome dev tools request enter image description here

Cypress request failed enter image description here

Any help here would be really appreciated - I've been going crazy!

Thanks so much,
Ollie

like image 540
Ollie Avatar asked Mar 18 '19 19:03

Ollie


1 Answers

Currently, Cypress cy.route can only stub network requests that use XHRs

Native HTML form elements don't use XMLHTTPRequest, hence you cannot use cy.route to stub it.

Most people don't run into this issue because using native HTML forms is not as common nowadays

Edit:

You are also waiting on the route, but haven't actually done anything in your test. Your test should look something like this:

  cy.route('GET',
      '**/getIncentives*',
      {info: {}, results: {}}
  ).as('oppty');

  // cypress code that would cause a network request.

  cy.wait('@oppty');

Also, make sure the request is of type:XHR: enter image description here

like image 120
bkucera Avatar answered Oct 09 '22 06:10

bkucera