当值为null时,Jasmine测试调用函数

时间:2013-08-14 14:45:14

标签: javascript unit-testing jasmine

我有一个函数可以将我返回到上一页。这工作正常,我想在茉莉花中测试它,但是当值为null时,我无法通过clickReturnToPage测试。

var ReturntoPage = {

    returnTo: function(fromPageObject){
        $('.btnholder').append('<input class="returnTo" type="button" value="Return to Page" />');
        ReturntoPage.clickReturntoPage();
    },

    disableReturnButton: function (disableFlag) {
        (disableFlag == true) ? $('.returnTo').addClass('disabledButton') : $('.returnTo').removeClass('disabledButton');
        $('.returnTo').prop('disabled', disableFlag);
    },

    clickReturnToPage: function(){
        var lastSearch = sessionStorage.getItem('prev');
        if(lastSearch != null){
            ReturntoPage.disableReturnButton(false);
        }else{
            ReturntoPage.disableReturnButton(true);
        }

        $(".returnTo").bind("click", function() {
            ReturntoPage.redirect();
        });
    },

    redirect:function(){
         lastSearch = sessionStorage.getItem('lastSearch');
         // got to that page
    },
};

这是我正在运行的测试。

describe("Return to page", function () {

    beforeEach(function () {
        setFixtures('<input class="returnTo" type="button" value="Return to Page" />');
    });

    it("should send false to disableReturnButton when last search is not null", function () {
        lastSearch = "aa";  
        spyOn(ReturntoPage, 'disableReturnButton');

        ReturntoPage.clickReturnToPage();
       // console.log("lastSearch = " + lastSearch);
        expect(ReturntoPage.disableReturnButton).toHaveBeenCalledWith(false);
    });

    it("should send true to disableReturnButton when when last search is null ", function () {
        lastSearch = null;
        spyOn(ReturntoPage, 'disableReturnButton');

        ReturntoPage.clickReturnToPage();
        //console.log("lastSearch = " + lastSearch);
        expect(ReturntoPage.disableReturnButton).toHaveBeenCalledWith(true);
    });


});

1 个答案:

答案 0 :(得分:2)

您无法覆盖函数中声明的变量,因此lastSearch = "aa"对您要测试的函数没有影响。由于lastSearch来自sessionStorage,您必须监视此问题并返回"aa"null

it("should send true to disableReturnButton when when last search is null ", function () {
    if(typeof sessionStorage === 'undefined'){
      sessionStorage = {getItem: jasmine.createSpy().andReturn(null)}
    }else{
      spyOn(sessionStorage, 'getItem').andReturn(null);          
    }
    spyOn(ReturntoPage, 'disableReturnButton');

    ReturntoPage.clickReturnToPage();
    //console.log("lastSearch = " + lastSearch);
    expect(ReturntoPage.disableReturnButton).toHaveBeenCalledWith(true);
});