如何通过上传文件来测试 Cypress 的 Web 服务 (API)?

Jon*_*nas 0 cypress

是否可以通过上传文件来使用 cypress 测试 Web 服务(api)。我尝试使用 cy.request,但不知何故它无法识别该文件:

cy.fixture('exampleTsv.tsv').then((tsvExmp) => {
    const blob = Cypress.Blob.binaryStringToBlob(tsvExmp, 'text');
    // Cypress.Blob.binaryStringToBlob(tsvExmp).then((blob) => {
    const formdata = new FormData();
    formdata.append('file', blob, 'exampleTsv.tsv');

    cy.request({
      url: 'APi-URL',
      method: 'POST',
      auth: {
        username: 'username',
        password: 'password',
      },
      body: {
        formdata,
      },
      headers: {
        'content-type': 'binary',
      },
    }).as('details');
    // Validate response code
    cy.get('@details').its('status').should('eq', 204);
    cy.get('@details').then((response) => {
      cy.log(JSON.stringify(response.body));
    });
  });
Run Code Online (Sandbox Code Playgroud)

我只得到:状态:404 - 未找到。但 api-url 和文件正在工作(用邮递员测试:使用 [body->binary->tsvExmp.tsv])

小智 6

您使用别名的方式不等待响应。cy.get('@details')不是等待,它读取当前值。

您应该用来.then()等待响应(请参阅cy.request

cy.request(...)
  .then(response => {
    cy.log(JSON.stringify(response.body));

    // Validate response code
    expect(response.status).to.eq(204)
  });
Run Code Online (Sandbox Code Playgroud)