Cypress:如何将API响应中的选定属性传递给另一个API请求?
我想使用Cypress进行API测试。我的目标是提取API响应的一部分并将其传递给另一个API请求。下面是一个示例代码:Cypress:如何将API响应中的选定属性传递给另一个API请求?,cypress,Cypress,我想使用Cypress进行API测试。我的目标是提取API响应的一部分并将其传递给另一个API请求。下面是一个示例代码: Cypress.Commands.add('createCustomer',()=>{ 返回请求({ 方法:“POST”, url:'api/v1/Customers', 标题:{ “内容类型”:“应用程序/json” }, 正文:{ //样本含量 } })。然后((响应)=>{ 返回新承诺(解析=>{ expect(response).property('status').
Cypress.Commands.add('createCustomer',()=>{
返回请求({
方法:“POST”,
url:'api/v1/Customers',
标题:{
“内容类型”:“应用程序/json”
},
正文:{
//样本含量
}
})。然后((响应)=>{
返回新承诺(解析=>{
expect(response).property('status').to.equal(201)
expect(response.body.property('id')。to.not.be.oneOf([null,“]))
const jsonData=response.body;
常量memberId=jsonData.id
解析(成员ID)
返回成员ID
})
})
})
通过这段代码,我得到了[object%20Object]作为结果
希望得到一些反馈。如果希望将响应从API请求1传递到API请求2,可以执行以下操作:
describe('Example to demonstrate API Chaining in Cypress', function () {
it('Chain two API requests and validate the response', () => {
//Part 1
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=sn',
}).then((response) => {
const location = response.body[0].title
return location
})
//Part 2
.then((location) => {
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=' + location
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body[0]).to.have.property('title', location)
})
})
})
})
那么您是在将
POST
生成的id添加到后续的GET
请求中
尝试在不使用承诺的情况下返回id,我认为此时您不需要承诺,因为响应已经到达
})。然后((响应)=>{
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;
返回成员ID;
})
获取的Url
cy.createCustomer().then(id => {
const url = `api/v1/Customers${id}`;
...
或
您的代码似乎在初始请求期间失败,而不是在后续操作期间。我远非Javascript专家,但您似乎有一些不必要的复杂性。试着像这样简化您的命令,看看您是否至少可以获得一个成功的请求:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
})
})
如果成功,请继续:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).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
})
})
您还可以提到您是如何使用从API 1到API 2的值的吗?在示例中,我只看到一个请求?它完全起作用了!非常感谢Marion!:)嗨,原来的请求有效。出于保密原因,我特意没有透露整个请求,但感谢您的检查。
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).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
})
})