Cypress test - Do not intercept api request

3.5k views Asked by At

I need to test some pages on a project and this project do some APIs call to external services.
I need to make sure that these calls are made and check if my page change accordingly to the response.

This is my test:

describe('A logged in user', () =>{
    it('can see his subscriptions', () => {
         ...... some checks .......

         cy.intercept('https://example.com/api/v2/user-panel/get-subscription').as('userSubscription');
         cy.wait('@userSubscription', { timeout: 35000 }).then(() => {

            cy.contains('some text');            
         });
    });
});

When I run the code seems that it can't se the API call but the page content change correctly.
This is the cypress response:

Timed out retrying after 35000ms: cy.wait() timed out waiting 35000ms for the 1st request to the route: userSubscription. No request ever occurred.

I tried to increase the timeout, event if the page loads in 1 second, but the result is the same.
There is something am I missing?

1

There are 1 answers

0
Fody On BEST ANSWER

Doing the cy.wait() right after the cy.intercept() is not going to work.

Whatever triggers the API calls (a cy.visit() or a .click()) must occur after the intercept has been set up, and it therefore is ready to catch the API call.

From the Network Requests docs

cy.intercept('/activities/*', { fixture: 'activities' }).as('getActivities')
cy.intercept('/messages/*', { fixture: 'messages' }).as('getMessages')

// visit the dashboard, which should make requests that match
// the two routes above
cy.visit('http://localhost:8888/dashboard')

// pass an array of Route Aliases that forces Cypress to wait
// until it sees a response for each request that matches
// each of these aliases
cy.wait(['@getActivities', '@getMessages'])

// these commands will not run until the wait command resolves above
cy.get('h1').should('contain', 'Dashboard')