进行异步调用以从量角器内的 REST 端点获取测试数据的正确方法?

Correct way to do async calls to get test data from REST end points inside Protractor?

我们正在使用 Protractor 并使用 Jasmine 作为 BDD 框架进行端到端 UI 测试。我们需要 UI 的文本根据来自 REST API 的数据进行验证,为此我们正在使用 Axios!! 这是正确的方法吗? 示例代码如下:

import axios from "axios";

describe("Some test for ", () => {

beforeEach(function(done) {
  axios
    .get(
     "******************"
    )
    .then(response => {
      data_file = response.data;
      done();
    });
});

it("some spec ", done => {
  expect($('#someId').getText()).toBe(data_file.someData);
  done();
});

});

我们可以在 Protractor 中使用 Chakram 而不是 Jasmine 中的 Axios 来获取数据吗?

如果上述方法是错误的,那么针对来自 REST 端点的数据测试 UI 的正确方法是什么? (Chai + Mocha + Chakram + Protractor)或其他什么?

有可能。 done() 回调告诉 Jasmine 你正在做一个异步任务;但是,您应该小心捕捉错误。

加入done.fail

import axios from "axios";

describe("Some test for ", () => {

  beforeEach(function(done) {
    axios
      .get(
       "******************"
      )
      .then(response => {
        data_file = response.data;
        done();
      })
      // if the above fails to .get, then we should catch here and fail with a message
      .catch(error => {
        done.fail('axios.get failed to execute');
      });
  });

更好的方法。使用异步/等待

在您的 Protractor 配置中,您需要添加 SELENIUM_PROMISE_MANAGER: false 以启用异步/等待。现在这将要求您等待所有承诺。

import axios from "axios";

describe("Some test for ", () => {

  beforeEach(async () => {
    try {
      const data_file = await axios.get("******************").data;
    } catch (e) {
      console.error('axios.get failed to execute');
      throw e;  // throwing errors should fail the spec.
    }
  });

  it("some spec ", async () => {
    // .getText returns a Promise<string> so you'll need to await it
    // to get the string value.
    expect(await $('#someId').getText()).toBe(data_file.someData);
  });  
});