簡體   English   中英

茉莉+異步功能

[英]Jasmine + Async functions

這是我的代碼:

'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 ,第二個請求中的unitID保持為0。

可以顯示如何用async / await或Promises實施解決方案嗎? 謝謝!

出於調試原因,我做了console.log。 現在它打印:
Result 2 - 0
Result 1 - 59dffdgfdgfg45545g

您不應以一種測試的輸出進入另一種測試的方式編寫測試。每個“測試”都應獨立。

相反,您應該進行兩次調用(嵌套調用)以獲取unitID的值,或者理想情況下,您應該模擬服務以返回“ it”期望的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM