Javascript 使用Jasmine进行异步回调测试
我正在尝试测试一个模块(使用browserify绑定),该模块执行XMLHttpRequest。该模块看起来像:Javascript 使用Jasmine进行异步回调测试,javascript,asynchronous,callback,jasmine,browserify,Javascript,Asynchronous,Callback,Jasmine,Browserify,我正在尝试测试一个模块(使用browserify绑定),该模块执行XMLHttpRequest。该模块看起来像: module.exports = function(year, cb) { var xhr = new XMLHttpRequest(); xhr.open('GET', encodeURI('data/' + year + '.json')); xhr.onload = function() { if (xhr.status === 200) { v
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();
});
});
我的茉莉花测试看起来像:
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();
});
});
我看到过这个问题,看起来完全一样,但仍然不起作用
对于countyList
,我得到了未定义的。我的茉莉花产量是:
did ajax call respond
X should return
Expected undefined not to be undefined. (1)
谢谢你的帮助 您的done()
位置错误。它必须在传递给县的回调函数中
:
beforeEach(function(done) {
counties(2015, function(data) {
countyList = data;
done();
});
});
这将确保it
方法仅在执行done
后调用,因此,在数据
返回后,并且您已经填充了countyList
。这样我就更接近了,谢谢。但是现在错误是:error:Timeout-在jasmine.DEFAULT\u Timeout\u INTERVAL指定的超时内未调用异步回调。(1)
我认为这种解决方案不会出现这种情况。有什么想法吗?你一开始就试过设置这个变量吗?也许,xhr的xhr
比Jasmine等待它的时间要长。例如,您可以尝试在每次调用之前将其设置为10000
。但是,比这要好得多:您可以使用ES7的async/await
,然后通过Babel传输它们。。。“您尝试过在开始时设置此变量吗?可能xhr比Jasmine等待它花费的时间要多。例如,您可以尝试在Beforeach/it调用之前将其设置为10000。”@awolfe76例如:Jasmine.DEFAULT\u TIMEOUT\u INTERVAL=10000;beforeach(函数(done){/*(…)*/});它('should(…)',function(done){/*(…)*/})
,明白了吗?您可以向beforeach传递第二个参数来设置超时。e、 g.beforeach(function(){//do something}.3000);