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

Cypress: How do I pass a selected property from API response to another API request?

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

I would like to use Cypress for API testing. My goal is to extract a part of the API response and pass it to another API request. Here's a sample code:

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
        })
    })
})

With this code, I am getting [object%20Object] as the result. enter image description here

Hoping for some feedback.

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

So you are adding the id generated by the POST to a subsequent GET request?

Try returning the id without using a Promise, I don't think you need one at that point since the response has already arrived.

}).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;
})

Url for GET

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

or

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}`;
  ...