I\'m really not sure how to approach testing this? (spyOn?)
function reloadPage() {
$(\'#logo\').click(function() {
location.reload();
})
}
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:
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.