[英]Async with callback testing with Jasmine
我正在尝试测试执行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();
};
我的茉莉花测试看起来像:
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();
});
});
我已经看到了这个问题- 为什么Jasmine不在这个异步测试中执行它? -这似乎是完全一样的东西,但仍然无法正常工作。
我对countyList
undefined
。 我的茉莉花输出是:
did ajax call respond
X should return
Expected undefined not to be undefined. (1)
谢谢你的帮助!
您的done()
在错误的位置。 它必须在传递给counties
的回调函数中:
beforeEach(function(done) {
counties(2015, function(data) {
countyList = data;
done();
});
});
这将确保it
的方法才会被调用后done
执行,所以,后data
又回来了,你已经有countyList
填充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.