Cypress API testing. Can not find property

Viewed 56

I am developing Cypress tests for my API. The response from my API in Postman is below:

{"infected" : false}

And my Cypress test is below:

describe("Testing the result after scanning file", () => {
  it("Scan file", function () {
    //Declarations
    const fileName = 'example.json';
    cy.fixture(fileName, 'binary')
    .then((file) => Cypress.Blob.binaryStringToBlob(file))
    .then((blob) => {
      const formData = new FormData();
      formData.append("file", blob, fileName);
      cy.request({
        method: 'POST',
        headers: {
          'content-type': 'multipart/form-data'
        },
        body: formData,
        url: '/scan'
      }).then(response => {
        console.log('the response is: ', response.body)       
        expect(response.body).to.have.property('infected').and.eq(false);
      });
    })
  });
});

In my browser, the Cypress test fails with the message:

assert expected {} to have property infected

I really have already broken my brain with this issue and still have no clue how to tackle it. Can anybody give me an idea what is going wrong?

2 Answers

Try converting the response to json, you may be seeing a string version of the data.

Postman output will not be helpful, it could be converting automatically in the background.

cy.request({
  ...
})

.then(response => response.json())
// OR
// .then(response => response.body.json())

.then(data => {

  console.log('the data is: ', data)               // better debug tool than Postman

  expect(data).to.have.property('infected').and.eq(false);
});

I finally figured out what is wrong. The request body was stored as ArrayBuffer. So I had co convert it to JSON firstly:

const json = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(response.body))); 

And my answer is below:

describe("Testing the result after scanning file", () => {
  it("Scan file", function () {
    //Declarations
    const fileName = 'example.json';
    cy.fixture(fileName, 'binary')
    .then((file) => Cypress.Blob.binaryStringToBlob(file))
    .then((blob) => {
      const formData = new FormData();
      formData.append("file", blob, fileName);
      cy.request({
        method: 'POST',
        headers: {
          'content-type': 'multipart/form-data'
        },
        body: formData,
        url: '/scan'
      }).then(response => {
        const json = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(response.body)));
        expect(response.status).to.equal(200);
        expect(json).to.have.property('infected').and.eq(false);
      })
    })
  });
});
Related