与Jasmine的回调测试异步

时间:2015-11-17 00:06:04

标签: javascript asynchronous callback jasmine browserify

我正在尝试测试执行XMLHttpRequest的模块(使用browserify进行捆绑)。该模块看起来像:

module.exports = function(year, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', encodeURI('data/' + year + '.json'));
  xhr.onload = function() {
    if (xhr.status === 200) {
      var counties = JSON.parse(xhr.responseText);
      cb(counties);
    } else {
      cb(xhr.status);
    }
  };
  xhr.send();
};

我的Jasmine测试看起来像:

var counties = require('myModule');

describe('did ajax call respond', function() {
  var countyList;

  beforeEach(function(done) {
    counties(2015, function(data) {
      countyList = data;
    });
    done();
  });

  it('should return', function(done) {
    console.log(countyList);
    expect(countyList).not.toEqual({});
    expect(countyList).not.toBeUndefined();
    done();
  });
});

我已经看到了这个问题 - Why is Jasmine not executing it() on this async test? - 这似乎完全相同,但它仍然没有用。

undefined我得到countyList。我的茉莉花产量是:

did ajax call respond
    X should return
        Expected undefined not to be undefined. (1)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您的done()位置错误。它必须位于传递给counties的回调函数中:

beforeEach(function(done) {
  counties(2015, function(data) {
    countyList = data;
    done();
  });
});

这将确保it方法仅在done执行后调用,因此,在data返回后,您已经填充了countyList