Warm tip: This article is reproduced from serverfault.com, please click

其他-赛普拉斯:如何将选定属性从API响应传递到另一个API请求?

(其他 - Cypress: How do I pass a selected property from API response to another API request?)

发布于 2020-11-30 20:48:45

我想使用赛普拉斯进行API测试。我的目标是提取一部分API响应并将其传递给另一个API请求。这是一个示例代码:

Cypress.Commands.add('createCustomer', () => {
    return cy.request({
        method: 'POST',
        url: 'api/v1/Customers',
        headers: {
            'Content-Type': 'application/json'
        },
        body: {
            // sample content
        }
    }).then((response) => {
        return new Promise(resolve => {        
            expect(response).property('status').to.equal(201)
            expect(response.body).property('id').to.not.be.oneOf([null, ""])
            const jsonData = response.body;
            const memberId = jsonData.id
            resolve(memberId)
            return memberId
        })
    })
})

有了这段代码,我得到了[object%20Object]作为结果。 在此处输入图片说明

希望得到一些反馈。

Questioner
sporkswife
Viewed
0
Marion Morrison 2020-12-01 19:29:21

因此,你POST要将生成的ID添加到后续GET请求中吗?

尝试在不使用Promise的情况下返回ID,由于响应已经到达,因此我认为你此时不需要一个ID。

}).then((response) => {
  expect(response).property('status').to.equal(201)
  expect(response.body).property('id').to.not.be.oneOf([null, ""])
  const jsonData = response.body;
  const memberId = jsonData.id;
  return memberId;
})

GET的网址

cy.createCustomer().then(id => {
  const url = `api/v1/Customers${id}`;
  ...

或者

cy.createCustomer().then($id => {
  const id = $id[0];       // Not quite sure of the format, you may need to "unwrap" it
  const url = `api/v1/Customers${id}`;
  ...