Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine unit testing window.onbeforeunload

I am trying to write some unit testing, but they are failing. Can you suggest me the right way to do?

show(contactId: string, phoneNumber: string, contactType: string, section: string, memberId: string) {
        this.$window.onbeforeunload = () => "";
        $('.disabledcalldialog').on("click", e => {
            this.$window.alert('Please close call dialog and try.');
            e.preventDefault();
        });

My spec file is like

beforeEach(() => {
        inject(($rootScope: ng.IScope, $window) => {
    spyOn($window, 'onbeforeunload');
            $(window).trigger('onbeforeunload');
  });
  it('should be able to call when changing URL', () => {
        
        expect($window.onbeforeunload).toHaveBeenCalled();

Karma throwing error message like " TypeError: Unable to get property 'onbeforeunload' of undefined or null reference";

like image 410
John Avatar asked Sep 02 '25 16:09

John


1 Answers

In your service:

setUpBeforeunload(): void {
  window.addEventListener('beforeunload', this.closeConnection);
}

And onto unit testing with Jasmine:

describe('setUpBeforeunload', () => {
  it('should set up window eventListener', () => {
    spyOn(window, 'addEventListener');
    service.setUpBeforeunload();
    expect(window.addEventListener).toHaveBeenCalledWith('beforeunload', service.closeConnection);
  });

  it('should call closeConnection()', () => {
    spyOn(service, 'closeConnection');
    service.setUpBeforeunload();
    window.dispatchEvent(new Event('beforeunload'));
    expect(service.closeConnection).toHaveBeenCalled();
  });
});
like image 194
Boris Yakubchik Avatar answered Sep 04 '25 04:09

Boris Yakubchik