单击按钮时拦截呼叫

tes*_*t11 1 cypress

我有以下步骤

  1. 点击按钮
  2. 单击按钮时,将发送保存请求
  3. 网站导航到其他页面

现在我需要拦截发送到后端的请求以获取其他页面上未显示的信息(例如预约日期,包括时间戳和区域)

我有以下代码

    let date = ''
    cy.intercept('POST', '**/appointments/v1', (req) => {
        // make an assertion on the payload contents
        expect(req.body).not.to.be.null
        console.log(req.body['date'])
        date = req.body['date']
    }).as('appointment')
    cy.get('[data-cy="appointment-confirm"]').should('exist').find('button')
        .click({force: true})
    cy.wait('@appointment')
Run Code Online (Sandbox Code Playgroud)

请求在上述代码中被拦截,但不会导航到下一页,因为我根本没有单击该按钮。请求的数据也不会保存到后端。

我看起来拦截的请求正在被停止

我也用过

let date = ''
cy.intercept('POST', '**/appointments/v1', (req) => {
    // make an assertion on the payload contents
    expect(req.body).not.to.be.null
    console.log(req.body['date'])
    date = req.body['date']
}).as('appointment')
cy.get('[data-cy="appointment-confirm"]').should('exist').find('ion-button')
    .click({force: true}).then(()=>{
    cy.wait('@appointment')
})
Run Code Online (Sandbox Code Playgroud)

我也有特雷德

    cy.intercept('POST', '**/appointments/v1', (request) => {
        expect(request.body).not.to.be.null
        console.log(request.body['date'])
        date = request.body['date']
        request.continue()
    }).as('appointment')
Run Code Online (Sandbox Code Playgroud)

但我发现了同样的问题,拦截的请求现在返回 400 Bad request

在此输入图像描述

mon*_*nti 5

IMO,实际上你的代码几乎是正确的,我建议你尝试这样的事情

cy.intercept({ method: 'POST', url: '**/roles' }).as('responseRole')

// after intercept you can click the button
cy.get('button').click()

// and wait for cypress to get the result as alias
cy.wait('@responseRole').then(({ request, response }) => {
  console.log(request.body)
  console.log(response.body)
})
Run Code Online (Sandbox Code Playgroud)