I tried intercept a POST request in my cypress test , but when i put a "json" as a fixture, cypress give the error "Unexpected end of json input", how can i pass the variable as a json data ?
JSON (percentage.json):
[
{
"totalPoints": 1,
"corretas": 1,
"totalIncorretas": [],
"percentage": 25
},
{
"totalPoints": 1,
"corretas": 1,
"totalIncorretas": [],
"percentage": 100
}
]
Test:
it('displays game over screen when user cannot make at least 63%', () => {
var case1 = []
cy.fixture('percentage.json').then((testData) => {
case1 = testData[0]
cy.log(case1)
})
cy.visit('http://localhost:5173/game_finished')
cy.intercept("POST", "http://localhost:3000/api/visitantes/sumuserpoints", {
fixture: `${case1}`
})
})
the log of "case1" variable after the assignment results in a object with 4 keys (like the json), but gives the error mencioned before
CodePudding user response:
I see a few corrections you could make
Fixture option is a name
The intercept isn't correct, when you pass a fixture
option it should be the name of the fixture file not the content
See With a fixture
// requests to '/users.json' will be fulfilled // with the contents of the "users.json" fixture cy.intercept('/users.json', { fixture: 'users.json' })
Using a static response
Technically you could use the value in variable case1
as the body for a stubbed intercept,
See With a StaticResponse object
cy.intercept("POST", "http://localhost:3000/api/visitantes/sumuserpoints", case1)
Avoiding the asynchronous trap
But in your code case1
will still be empty because the fixture is read asynchronously. So the intercept will be set before case1
receives a value.
Wrap it inside a .then()
to handle the asynchronous problem.
cy.then(() => {
cy.intercept("POST", "http://localhost:3000/api/visitantes/sumuserpoints", case1)
})