我想使用赛普拉斯进行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]作为结果。
希望得到一些反馈。
因此,你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}`;
...
完全有效!非常感谢Marion!:)