最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cypress cy.request expect to throwfail - Stack Overflow

programmeradmin2浏览0评论

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: `/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

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
Share Improve this question edited Mar 21, 2021 at 2:42 user14783414 asked Mar 20, 2021 at 22:31 Nikita FedyashevNikita Fedyashev 19k13 gold badges56 silver badges106 bronze badges 1
  • Are you using Cypress 6? The intercept command might be useful for you. docs.cypress.io/api/commands/… – Shafiq Jetha Commented Mar 21, 2021 at 5:54
Add a comment  | 

1 Answer 1

Reset to default 15

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.

发布评论

评论列表(0)

  1. 暂无评论