Location reload in Jasmine

前端 未结 1 917
心在旅途
心在旅途 2021-01-14 02:47

I\'m really not sure how to approach testing this? (spyOn?)

function reloadPage() {
  $(\'#logo\').click(function() {
    location.reload();
  })
}


        
相关标签:
1条回答
  • 2021-01-14 03:32

    The reason you may be unsure about how to test this piece of code is because it's doing 2 different things and you should break it up into smaller chunks.

    I see two distinct functions here:

    • click event handling
    • reload page

    So why not break up the logic like so?

    function reloadPage() {
        location.reload();
    }
    
    function bindEvents() {
        $('#logo').click(reloadPage);
    }
    

    Now you can test them separately using Spies:

    describe('when the logo is clicked', function() {
       var logo;
       var handlers;
       beforeEach(function() {
           handlers = {
               locationReload: location.reload, // handle for location.reload()
               reloadPage: reloadPage      // handle for your reloadPage()
           };
    
           logo = $('#logo').click(reloadPage);
    
           // attach Spy on reloadPage() and let the function call through
           spyOn(handlers, 'reloadPage').and.callThrough();
    
           // attach Spy on location.reload() 
           spyOn(handlers, 'locationReload');
    
       });
    
       it('will execute reloadPage function', function() {
            logo.trigger('click');
            expect(handlers.reloadPage).toHaveBeenCalled();
       });
    
       it('will reload the page', function() {
            logo.trigger('click');
            expect(handlers.locationReload).toHaveBeenCalled();
       });
    
       afterEach(function() {
           // clean up event bindings after each test
           logo.off('click');
       });
    
    });
    

    There's not much need to test that the reloadPage handler was correctly added to the #logo's click event because the test is simulating a .click() and checking if reloadPage gets called or not.

    So most likely you'd only need to have the it('will reload the page') spec, not both.

    0 讨论(0)
提交回复
热议问题