cy.intercept() not stubbing API in Cypress

16,766

Solution 1

I managed to get stubbing working with the pattern @eric99 gave,

cy.intercept(
  'GET',
  'https://jsonplaceholder.typicode.com/todos/1',
  {
    statusCode: 200,
    body: {
      message: 'Request successful',
      result: ['my-data']
    }
  }
)
.as('typicode')

cy.visit('https://jsonplaceholder.typicode.com/')
cy.get('#run-button').click();

cy.wait('@typicode')
.then((interception) => {
  console.log('interception', interception)
})

The page shows the stub information,

{
    "message": "Request successful",
    "result": [
        "my-data"
    ]
}

Solution 2

I had this issue before then I found out that it was caused by CORS policy.

There are some solutions to overcome this issue:

Share:
16,766

Related videos on Youtube

sofina
Author by

sofina

Updated on October 01, 2022

Comments

  • sofina
    sofina over 1 year

    When I use cy.intercept(), the API does not stub.

    Any help would be appreciated, Thank you

    cy.intercept('GET',
              `${API}farm/list`,
              {
             body:{           
                   statusCode: 200,
                   message: 'Request successful',
                   result: seededFarmList
                   }
              });
    

    I am importing the fixture file like this:

    import { seededFarmList } from '../../../../../fixtures/farm';

    My API response looks like this:

    {
     "statusCode": 200, 
    "message": "Request successful", 
    "result": 
    [ 
      { "id": 1 "farmName": "ABCD", },
      { "id": 2 "farmName": "EFGH", }
    ]
    }
    
  • sofina
    sofina over 3 years
    Richard, what format is your data, the one you assigned to the result? I did the same way you did, but still not working
  • Richard Matsen
    Richard Matsen over 3 years
    The format of the data is not relevant to whether or not the the cy.intercept() function stubs (except when it has a syntax problem like a missing comma between properties). Any well-formed object on the body property should be returned to the app. It looks like your seedFarmList is problematic.
  • Wilt
    Wilt about 2 years
    Thanks! I currently feel like I should bang my head against the wall a few times.