首页 > 解决方案 > 在测试中使用回调排序

问题描述

我正在做一个需要令牌才能运行的测试。需要将此标记传递给比较函数。但我不了解如何等待令牌才能继续执行测试。我是新的JS,所以很抱歉。这是我的测试代码:

  describe('Offline Comparison', function () {
  token = getToken('appName');
  console.log('Token' + token);
  files.forEach(function (file) {
    it('Comparando file ' + file, function (done) {
      this.timeout(15000);
      const id = file.split('./screenshots/')[1];
      compare(file, id, token, function (response) {
        console.log(JSON.stringify(response, null, 4));
        expect(response.TestPassed).to.be.true;
        done();
      });
    });
  });
});

function getToken(applicationName, callback) {
  request.post('http://localhost:8081/token',
    {
      json: {
        application_name: applicationName
      }
    },
    (error, response, body) => {
      console.log('Token: ' + body.Token);
      return callback(body.Token)
    });
}

标签: javascript

解决方案


您的getToken()函数是异步的并且需要回调。您不能只是调用它并期望并回答,您需要向它传递一个回调函数,它将以令牌作为参数进行回调。你需要这样的东西来获取令牌:

describe('Offline Comparison', function () {
  getToken('appName', function(token){   // <- pass getToken a callback
      console.log('Token' + token);      // <- token should now be available
      files.forEach(function (file) {
        it('Comparando file ' + file, function (done) {
          this.timeout(15000);
          const id = file.split('./screenshots/')[1];
          compare(file, id, token, function (response) {
              console.log(JSON.stringify(response, null, 4));
              expect(response.TestPassed).to.be.true;
              done();
          });
        });
      });
    }); 
});

推荐阅读