如何对调用getJSON的JavaScript函数进行单元测试 [英] How to unit test javascript function that calls getJSON

查看:88
本文介绍了如何对调用getJSON的JavaScript函数进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在单元测试中苦苦挣扎了2天了,关于异步测试,我无法实现某些目标.我是单元测试的新手,我不明白为什么这不起作用.

I've been struggling with unit test for 2 days now and there is something I can't achieve regarding async test. I'm new to unit test and I don't understand why this doesn't work.

我有一个文件login.js,该文件调用$ .getJSON(URL,数据,函数),并返回具有登录状态(成功"或失败")的字符串. 对$ .getJSON的调用使用mockjax来获取数据(它包装了ajax调用).

I have a file login.js that calls a $.getJSON(url, data, function) and returns a string with the status of login ("success" or "fail"). The call to $.getJSON uses mockjax to get the data (it wraps an ajax call).

当使用jQuery click事件从测试网页调用登录功能时,登录功能正常. 但是现在我正在尝试使用Qunit和PhantomJS进行无头测试.

The login function works ok, when called from a test webpage using jQuery click event. But now I'm trying to run headless test using Qunit and PhantomJS.

似乎问题在于测试没有等待$ .getJSON调用来获取结果(即使使用超时). 有什么线索吗? 这是代码.

It seems the problem is that the test is not waiting for the $.getJSON call to get the result (even when using a timeout). Any clues? Here is the code.

login.js

var login = function(user, pass){
    $.getJSON("loginURL", {"user":user, "pass":pass}, function(response){
       if(response.status === "success"){
           //do something
           return "success";
       } 
       else{
           //do something else
           return "fail";
       } 
    });
};

test.js

test("Test login", function(){
    var user = "user1", pass = "pass1";
    var done = assert.async();
    var result = login(user, pass);
    setTimeout(function(){
    assert.equal(result, "success", "expect login succeded");
    done();
    },1000);
});

在测试结果中我得到:

预期:成功"

结果:未定义

推荐答案

您的login函数应该是异步的,因为其结果取决于服务器的响应.

Your login function should be asynchronous, because its result depends on a response from server.

所以让我们这样重写函数:

So let's rewrite the function like this:

function login(user, pass, done) {
    $.getJSON(..., function (res) {
        done(res.status == 'success')
    })
}

然后您可以像这样测试(假设是摩卡咖啡):

Then you can test like this (assuming mocha):

describe('...', function () {
    it('login()', function (done) {
        login('user', 'pw', function (isLoggedIn) {
            assert(isLoggedIn)
            done()
        })
    })
})

这篇关于如何对调用getJSON的JavaScript函数进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆