I want to test the following use case:
cy.intercept()
methodcy.wait('@myapi').its('response.statusCode').should('eq', 200);
statusCode
400 and validate the response body to contain the error messageHow to do this in cypress? Any ideas? :D
I tried to do something like this:
cy.intercept('POST', regexHelpers.getCartURIRegex(voucherCode)).as("redeemVoucher");
cy.get('[data-cy="buttonRedeemVoucher"]').click();
// cy.wait('@redeemVoucher').its('response.statusCode').should('eq', 200);
cy.wait('@redeemVoucher').then(function(interception) {
expect(interception.response.statusCode).to.eq(200);
const url = interception.request.url;
cy.request({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}}).its('status').should('eq', 400);
});
But in this case I get 400
error code - bad request already at the lineexpect(interception.response.statusCode).to.eq(200);
The first call to API should return 200, but the second call with the same voucher should return 400.
I am confused why is it returning 400 already at this line:
expect(interception.response.statusCode).to.eq(200);
[EDIT]
I managed to do this:
cy.intercept('POST', regexHelpers.getCartURIRegex(voucherCode)).as("redeemVoucher");
cy.get('[data-cy="buttonRedeemVoucher"]').click();
cy.wait('@redeemVoucher').its('request.url').as('voucherUrl').then(function() {
cy.request({
method: 'POST',
url: this.voucherUrl,
failOnStatusCode: false,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}}).its('status').should('eq', 400);
});
But I don't know how to also check here that first call response code was 200?
Does anybody has an idea? :D
You can check the first response call with .should(callBack)
cy.wait('@redeemVoucher')
.should(interception => expect(interception.response.statusCode).to.eq(200))
.its('request.url').as('voucherUrl').then(function() {
cy.request({
method: 'POST',
url: this.voucherUrl,
failOnStatusCode: false,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}}).its('status').should('eq', 400);
});
But your first example would also work, provided you added failOnStatusCode: false
to the request.
I also did the following which also worked:
cy.wait('@redeemVoucher').should(({request, response}) => {
expect(response.statusCode).to.eq(200);
cy.request({
method: 'POST',
url: request.url,
failOnStatusCode: false,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}}).should((response) => {
expect(response.status).to.eq(400);
expect(response.body.errors[0].message).to.eq('Voucher cannot be redeemed: ' + voucherCode);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.