Cypress cy.request 期望抛出/失败

Nik*_*hev 7 javascript chai cypress

有什么方法可以编写一个测试用例,以期望cy.request在某些参数上失败(非 2** 响应)?

我尝试使用以下代码片段:

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

但它失败了:

AssertionError
expected [Function] to throw an error
Run Code Online (Sandbox Code Playgroud)

这是仅 API 的项目,所以基本上我只cy.request在任何地方使用。

如果没有expect功能块,它会失败并显示:

CypressError
cy.request() failed on

The response we received from your web server was:

  > 500: Internal Server Error
Run Code Online (Sandbox Code Playgroud)

小智 15

要检查响应的状态是否不是 200,请添加该failOnStatusCode: false选项。

Cypress 捕获内部错误并且不会重新抛出它们,因此expect(...).to.throw不会看到任何内容。

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
})
Run Code Online (Sandbox Code Playgroud)

500: Internal Server Error是特定于您的 API 的,但cy.request正在执行其工作,因为默认情况下它被配置为在请求失败时使测试失败。