I am using Typescript for my Cypress test.
This is my function:
createOrder: (body) => {
let order: { id: any }
cy.request({
method: 'POST',
url: '/order',
body: body
}).then(response => {
let res = response.body.Order
order.id = res.id
})
return order
},
Upon execution I am getting the error: Cannot set properties of undefined (setting 'id')
What am I missing here? I have seem to declare id
already in my understanding.
CodePudding user response:
let order: { id: any }
defines a type for order
but does not give it a value.
Try initializing it let order: {id: any} = {id: ""}
and avoid using any
(using any
disables type checking for the variable/property and gets you in these sort of issues)
CodePudding user response:
Aside from the primary question, please note that your method will never return the value from the response.
The POST request is asynchronous, but the return of the method is synchronous and it will always return the original empty value.
To solve that, you must return the request itself and also the the id
inside the .then()
callback.
createOrder: (body): Chainable<{ id: string }> => {
order: {id: string} = {id: ''}
return cy.request({ // returns the result of the request
method: 'POST',
url: '/order',
body: body
}).then(response => {
const res = response.body.Order
order.id = res.id
return order // returns order as the modified response
})
}
Once you have an asynchronous section in the code, everything after it must be treated asynchronously as well, so this is how you would use the method
it('tests with createOrder', () => {
...
myPageObject.createOrder(body).then(order => {
...
})
})