Jasmine如何为简单的jQuery Ajax函数编写测试用例

时间:2015-09-17 05:57:47

标签: javascript jquery ajax unit-testing jasmine

Jasmine的新手。我正在尝试编写一个片段来测试我的功能 这是用jQuery ajax写的。

以下是摘录

function submitLoginForm(e){
    e.preventDefault();
    try {
        var data = $("form").serialize();
        $.ajax({
            type: "POST",
            data: data,
            url : "/auth/login",
            dataType: 'json',
            success: function(data){
                submitLoginFormSuccess(data)
            },
            error: function( xhr, status, errorThrown ){
                submitLoginFormError(xhr, status, errorThrown)
            }
        });
    }catch (e) {
        throw new Error(e.message);
    }
}

,回调函数

function submitLoginFormSuccess(data){
    if(data.status == "success"){
        window.location = "/app"
    }
    else{
        toastr["error"]("Invalid Credentials!")
    }
}
function submitLoginFormError(xhr, status, errorThrown){
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
}

请有人帮帮我。

我得到的问题是: -

  1. 事件未定义。

  2. 我不知道如何检查成功和失败的反应

  3. 更新 下面的片段运行正常。我该如何测试其他场景?

    describe("#submitLoginForm", function() {
    
        it("should make sure that all parameter of ajax is not changed", function() {
          spyOn($, "ajax");
          submitLoginForm(event);
          var result = $.ajax.mostRecentCall.args[0];
    
          expect(result.url).toEqual("/auth/login");
          expect(result.dataType).toEqual("json");
          expect(result.type).toEqual("POST");
    
        });
    
    });
    

0 个答案:

没有答案