茉莉花 + 异步功能



这是我的代码:

'use strict';
var unitID = 0;
var getById = function(generalOptions, specificOptions) {

describe('API tests for: ' + specificOptions.name, function() {
var url = generalOptions.baseUrl + specificOptions.route;

// GET all items
it('= = = GET ALL test for ' + specificOptions.name + ' return status 
code 200',  function(done) {
  generalOptions.request.get({
    url: url
  }, function(error, response, body) {
    expect(response.statusCode).toBe(200);
    expect(JSON.parse(body)).not.toBeFalsy();
    if (specificOptions.route == '/devices/') {
      var bodyJS = JSON.parse(body);
      unitID = bodyJS.devices[0].id;
    } else {
     unitID = '';
    }
    console.log('Result 1 - ' + unitID);
    done();
  });
});

//GET by ID
it('= = = GET by ID test for ' + specificOptions.name + ' return status code 200', function(done) {
  console.log('Result 2 - ' + unitID);
  generalOptions.request.get({
    url: url + unitID
  }, function(error, response, body) {
    expect(response.statusCode).toBe(200);
    expect(JSON.parse(body)).not.toBeFalsy();
    done();
      });
    });
  })
};
module.exports = getById;

我需要等待,而unitID将使用第一个 GET 请求进行更新,然后在下一个请求中使用。

问题是,它异步工作,并在第二个请求中unitID保持 0。

可以展示如何使用异步/等待或承诺实现解决方案吗?谢谢!

出于调试原因,我做控制台.log。现在它打印:

Result 2 - 0 Result 1 - 59dffdgfdgfg45545g

你不应该以一种测试的输出进入另一个测试的方式编写测试。每个"它"都应该是独立的。

相反,您应该调用

两次(嵌套调用(以实现unitID的值,或者理想情况下,您应该模拟服务以返回"it"所需的数据。

最新更新