Location reload in Jasmine

依然范特西╮ 提交于 2019-12-19 08:29:07

问题


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

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

Any advice would be great!


回答1:


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.



来源:https://stackoverflow.com/questions/23344058/location-reload-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!