javascript - 简单的 Jasmine 异步测试导致超时

标签 javascript testing asynchronous jasmine

我正在努力获得一个简单的测试以在模块中的异步函数上运行。我正在尝试着手测试,因此构建了一个工作模块并在 repl.it 中对其进行了手动测试

http://repl.it/7Qf

我的模块是这样的:

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/

相关文章:

android - 如果我的应用程序在后台运行,doInBackground 是否仍然运行?

javascript - 从 gjs 读取异步标准输出

javascript - JavaScript 中的 $ 符号是做什么用的

javascript - 在 JavaScript 中迭代 DOM 时关闭标签事件

javascript - 如何记录变量及其名称?

ios - Testflight SDK 和 iOS 模拟器 - 如何使用?

actionscript-3 - 如何在actionscript3中异步获取文件修改日期

javascript - 如何在 HTML 代码中阻止 PHP 内容?

linux - 如何在 bash 中测试程序? (功能测试)

node.js - Jest : how to restore to a previous mocked implementation (not the original)