我正在尝试测试执行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)
感谢您的帮助!
答案 0 :(得分:1)
您的done()
位置错误。它必须位于传递给counties
的回调函数中:
beforeEach(function(done) {
counties(2015, function(data) {
countyList = data;
done();
});
});
这将确保it
方法仅在done
执行后调用,因此,在data
返回后,您已经填充了countyList
。