我正在努力获得一个简单的测试以在模块中的异步函数上运行。我正在尝试着手测试,因此构建了一个工作模块并在 repl.it 中对其进行了手动测试
我的模块是这样的:
var weather = (function() {
var location;
var url = 'http://api.openweathermap.org/data/2.5/weather?units=metric&q=';
function getData(loc, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url+loc, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
callback(JSON.parse(xhr.statusText));
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
return {
getTemp: function(location, callback) {
getData(location, function(data) {
var temp = data.main.temp.toFixed(2);
callback(temp);
});
}
}
}());
我的测试套件如下所示:
describe("Weather Module", function() {
it('get temperature', function(done) {
weather.getTemp('coventry,uk', function(data){
console.log(data);
expect(data).toBe(2.66);
done();
});
});
});
我在运行此测试时遇到超时错误。谁能看出我哪里出错了?
编辑:我尝试了不同的方法但得到了同样的错误。
describe("Weather Module", function() {
beforeEach(function(done) {
this.temp = null;
weather.getTemp('coventry, uk', function(data) {
this.temp = data;
done();
});
});
it('should get temp', function() {
expect(this.temp).toBe(2.66);
});
});
我仍然收到此错误 Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
最佳答案
我遇到了同样的问题。发生这种情况是因为 Jasmine 的默认间隔设置为 5000 毫秒。
我在测试脚本文件的开头添加了以下行:
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;// set your time here
这意味着 Jasmine 将在测试失败之前等待 done() 函数 20 秒。
关于javascript - 简单的 Jasmine 异步测试导致超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748708/