赛普拉斯:如何访问POST请求的正文?

时间:2020-05-15 11:41:16

标签: integration-testing cypress

赛普拉斯是否可以检查POST请求的正文?

例如:我已经以表格形式输入了一些数据,然后按“提交”。 表单数据通过POST请求发送,与标题数据之间用空行分隔。

我想检查表格数据。如果包括了我输入的所有数据,并且它们正确无误。

赛普拉斯有可能吗?

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

xhr对象不包含传输的数据。

2 个答案:

答案 0 :(得分:3)

应该有可能。

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开发者工具中检查数据的方式。

This is how you can inspect your data in Chrome Developer Tool

在赛普拉斯中运行测试时,您应该会从Chrome开发人员工具中看到相同的内容。

You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress

答案 1 :(得分:1)

我正在谷歌搜索相同的问题,并在到达文档之前以某种方式降落在这里。

无论如何,您是否尝试过以下方法:

cy.wait('@login').should((xhr) => {
  const body = xhr.request.body

  expect(body).to.match(/email/)
})

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

祝你好运!