赛普拉斯-无法将response.body数据存储到JSON文件中

时间:2019-03-05 08:24:04

标签: cypress

我已经成功地使用FormData创建了POST XMLHttpRequest。现在,我需要捕获它的响应主体并将其存储在JSON文件中。

Cypress.Commands.add(
  "Post_Clients",
  (imagePath, imageType, attr1, attr2, attr1Val, done) => {
    cy.fixture(imagePath, "binary").then(imageBin => {
      Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        const data = new FormData();
        data.set(attr1, attr1Val);
        data.set(attr2, blob);
        xhr.open("POST", "https://api.teamapp.myhelpling.com/admin/clients");
        xhr.responseType = "json"
        xhr.setRequestHeader("accept", "application/json");
        xhr.setRequestHeader("access-token", accesstoken);
        xhr.setRequestHeader("client", client);
        xhr.setRequestHeader("expiry", expiry);
        xhr.setRequestHeader("token-type", tokentype);
        xhr.setRequestHeader("uid", uid);
        xhr.onload = function() {
          done(xhr);
        };
        xhr.onerror = function() {
          done(xhr);
        };
        xhr.send(data);
      });
    });
  }
);


it.only("API POSTing TEST", () => {
    cy.Post_Clients(
      "/images/clients/Golden JPEG.jpeg",
      "image/jpeg",
      "client[name]",
      "client[client_logo_attributes][content]",
      "Test Attr 1 Value is Hi!!!",
      resp => {
        cy.writeFile(
          "cypress/fixtures/POST API OUTPUT DATA/Client.json",
          resp.response
        );
        expect(response.status).to.eq(201);
      }
    );
  });

请注意,expect(response.status).to.eq(201);断言的效果很好。

以下代码在控制台中正确记录了正文

cy.log("Response Body", resp.response);
console.log("Response Body", resp.response);

响应正文为:-

{"client":{"id":452,"name":"Test Attr 1 Value is Hi!!!","client_logo":{"id":543,"path":"https://api.teamapp.myhelpling.com/uploads/client_images/6279486665-1551780183.","thumb":"https://api.teamapp.myhelpling.com/uploads/client_images/thumb_6279486665-1551780183.","medium":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","large":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","filename":"blob","ratio":1.78}}}

但是

cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",resp.response
);

不会将响应正文保存在Client.JSON文件中。

cy.writeFile在此代码中似乎不起作用。我已经通过验证了    传递JSON例如{“ A”:“ B”},但这也没有达到    JSON。

1 个答案:

答案 0 :(得分:0)

这是简单示例试试这个。

cy.request('https://jsonplaceholder.cypress.io/users')
.then((response) => {
cy.writeFile('cypress/fixtures/users.json', response.body)
})