4
votes

Is there any way to write a test case to expect cy.request to fail(non-2** response) on certain params?

I attempted to use the following snippet:

it('intentionally fails', () => {
  expect(
    () => {
      cy.request({
        method: 'POST',
        url: `https://valid.url/api/items`,
        body: {name: "foo"},
      })
    }
  ).to.throw('bar')
})

but it fails with:

AssertionError
expected [Function] to throw an error

This is API-only project, so basically I only use cy.request everywhere.

Without the expect function block it fails with:

CypressError
cy.request() failed on

The response we received from your web server was:

  > 500: Internal Server Error
1
Are you using Cypress 6? The intercept command might be useful for you. docs.cypress.io/api/commands/…Shafiq Jetha

1 Answers

5
votes

To check if the status of the response is not 200, add the failOnStatusCode: false option.

Cypress catches internal errors and does not re-throw them so expect(...).to.throw is not going to see anything.

cy.request({
  method: 'POST',
  // url: `https://valid.url/api/items`,
  url: 'http://example.com/api/items',
  body: {name: "foo"},
  failOnStatusCode: false
})
.then(response => {
  expect(response.status).to.be.gt(299)  // status returned is 404
})

The 500: Internal Server Error is specific to your API, but cy.request is doing it's job as by default it is configured to fail the test when the request fails.