如何在 cypress 中测试错误请求

问题描述 投票:0回答:4

我正在使用不正确的凭据测试 cypress 中 POST 方法的日志记录。这会返回 400 个错误请求,我需要对其进行测试。

这就是我所拥有的:

describe('Login API Test - Correct user login', () => {
  it('Validate the header', () => {
    cy.request({
      method: 'POST',
      url: 'https://myrAPI',
      auth: {
        username: 'user@user',
        password: 'user123',
      },
      headers: {
        'Authorization': 'Basic dXNlckB1c2VyOnVzZXI=',
        'Content-Type': 'text/plain'
      }
    }).then((response) => {
      // expect(response.body).to.exist // true
      // expect(response.body).('User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Error with Authentication Header. result =') // true
      // expect(response.headers).should.contain('text/plain; charset=utf-8')
      // expect(response.body).statusCode.should.equal(400)
      response.status.should.equal(400)
      //expect(response).to.have.property('headers')
    })
  }})

发送的请求:

Method: POST
URL: https://myapi
Headers: {
  "Connection": "keep-alive",
  "Authorization": "Basic dXNlckB1c2VyOnVzZXIxMjM=",
   "Content-Type": "text/plain",
   "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
  "accept": "*/*",
  "accept-encoding": "gzip, deflate",
  "content-length": 0
  }

这是我得到的回复:

Status: 400 - Bad Request
 Headers: {
  "content-length": "239",
   "content-type": "text/plain; charset=utf-8",
 "request-context": "appId=cid-v1:d994e38c-9493-4dd6-ac8c-5395bb9ce790",
   "date": "Tue, 02 Jul 2019 13:35:18 GMT"
}
 Body: User.Access: Exception occured:User.Access : CheckUser: Exception occurred:Exception when checkin...

我想知道响应或正文中的内容

javascript testing cypress bad-request
4个回答
37
投票

您的问题的答案在错误消息中:

如果您不希望状态代码导致失败,请传递选项:'failOnStatusCode: false'

因此,通过

failOnStatusCode: false
以免因错误状态代码而失败:

    cy.request({
        method: 'POST',
        url: 'https://myrAPI',
        failOnStatusCode: false,
        auth:
        {
            username: 'user@user',
            password: 'user123',
        },
        headers:
        {
            'Authorization': 'Basic dXNlckB1c2VyOnVzZXI=',
            'Content-Type': 'text/plain'
        }
    })

3
投票

我使用以下代码片段来显式检查状态代码:

        cy.request({
            url: '/url/returning/400/bad/request/status/code',
            failOnStatusCode:false,
        }).then((resp) => {
            expect(resp.status).to.eq(400)
        })

(来源自cypress 文档


0
投票

请添加以验证响应等于 400 期望(response.body).has.property(“statusCode”,400);


0
投票

我这样做了,它似乎有效,但我是 Cypress 和 JavaScript 的新手。

describe('My Tests', () => { it('Web Page - Open Welcome Page', => () { // verify page opens. cy.request({url: 'http://localhost:8080', failOnStatusCode: true}).its('status').should('equal', 200) cy.visit('http://localhost:8080', {failOnStatusCode: true}) }) })

© www.soinside.com 2019 - 2024. All rights reserved.