1

我有一个函数可以让我返回上一页。这很好用,我想在 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);
    });


});
4

1 回答 1

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);
});
于 2013-08-14T15:01:18.993 回答