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:
- https://docs.cypress.io/guides/guides/web-security.html#Set-chromeWebSecurity-to-false
- Both front-end and back-end should be on the same origin; e.g., HTTP://localhost:1000
Related videos on Youtube
Author by
sofina
Updated on October 01, 2022Comments
-
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 over 3 yearsRichard, 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 over 3 yearsThe 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 thebody
property should be returned to the app. It looks like yourseedFarmList
is problematic. -
Wilt about 2 yearsThanks! I currently feel like I should bang my head against the wall a few times.