javascript - Jasmine unit testing window.onbeforeunload - Stack Overflow

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

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();
        });

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";

Share Improve this question asked Nov 7, 2015 at 23:02 JohnJohn 411 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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();
  });
});

Have you tried:

$window.trigger('onbeforeunload');

instead of:

$(window).trigger('onbeforeunload');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745585763a4634529.html

相关推荐

  • javascript - Jasmine unit testing window.onbeforeunload - Stack Overflow

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

    8小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信