Jasmine单元测试window.onbeforeunload

4

我正在尝试编写一些单元测试,但它们一直失败。你能建议一下正确的做法吗?

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

我的规范文件如下:

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抛出错误信息,如“TypeError:无法获取未定义或空引用的属性'onbeforeunload'”;

2个回答

4

在您的服务中:

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

接下来我们要使用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();
  });
});

-1

你尝试过了吗:

$window.trigger('onbeforeunload');

而不是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接