简体   繁体   English

茉莉+异步功能

[英]Jasmine + Async functions

Here is my code: 这是我的代码:

'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;

I need to wait, while unitID will be updated with first GET request and then use in in the next request. 我需要等待,而unitID将通过第一个GET请求进行更新,然后在下一个请求中使用。

The problem is, that it works asynchronously and unitID in the second request stay 0. 问题是,它异步unitID ,第二个请求中的unitID保持为0。

Can show how to implement solution with async/await or Promises? 可以显示如何用async / await或Promises实施解决方案吗? Thanks! 谢谢!

For debugging reason I do console.log. 出于调试原因,我做了console.log。 For now it print: 现在它打印:
Result 2 - 0
Result 1 - 59dffdgfdgfg45545g

You should not write test in such fashion where output of one test goes into other.Each "it" should be independent. 您不应以一种测试的输出进入另一种测试的方式编写测试。每个“测试”都应独立。

Instead you should make call twice(nested call) to achieve the value of unitID or ideally you should mock the service to return the data that is expected by the "it". 相反,您应该进行两次调用(嵌套调用)以获取unitID的值,或者理想情况下,您应该模拟服务以返回“ it”期望的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM