【问题标题】:Cypress: How to access the body of a POST-request?赛普拉斯:如何访问 POST 请求的正文?
【发布时间】:2020-05-15 11:41:16
【问题描述】:

赛普拉斯有没有办法检查 POST 请求的正文?

例如:我在表格中输入了一些数据,然后按“提交”。 表单数据是通过 POST 请求发送的,由一个空行与 header-data 分隔。

我想检查表单数据。如果我输入的所有数据都包括在内并且它们是否正确。

赛普拉斯有可能吗?

cy.get('@login').then(function (xhr) {
    const body = xhr.requestBody;
    console.log(xhr);
    expect(xhr.method).to.eq('POST');
});

xhr-object 不包含传输的数据。

【问题讨论】:

    标签: integration-testing cypress


    【解决方案1】:

    应该可以的。

    describe('Capturing data sent by the form via POST method', () => {
    before(()=> {
        Cypress.config('baseUrl', 'https://www.reddit.com');
        cy.server();
        cy.route({
            method: 'POST',
            url: '/login'
        }).as('redditLogin');
    });
    it('should capture the login and password', () => {
        cy.visit('/login');
        cy.get('#loginUsername').type('username');
        cy.get('#loginPassword').type('password');
        cy.get('button[type="submit"]').click();
    
        cy.wait('@redditLogin').then(  xhr => {
            cy.log(xhr.responseBody);
            cy.log(xhr.requestBody);
            expect(xhr.method).to.eq('POST');
        })
    });
    

    });

    这是您在 Chrome 开发者工具中检查数据的方法。

    当您在 Cypress 中运行测试时,您应该会看到在 Chrome 开发者工具中看到的相同内容。

    【讨论】:

    • 您将如何验证状态?
    【解决方案2】:

    我在谷歌上搜索了同样的问题,并在到达文档之前不知何故登陆了这里。

    不管怎样,你有没有尝试过类似的东西:

    cy.wait('@login').should((xhr) => {
      const body = xhr.request.body
    
      expect(body).to.match(/email/)
    })
    

    我还没有使用multipart/form-data 编码的请求对其进行测试,但我怀疑您也会以这种方式找到请求正文。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 2020-05-09
      • 2022-11-02
      • 2022-06-29
      • 2020-10-28
      • 2021-09-28
      • 2021-10-26
      相关资源
      最近更新 更多