【问题标题】:Jasmine unit testing window.onbeforeunloadJasmine 单元测试 window.onbeforeunload
【发布时间】:2015-11-07 23:02:36
【问题描述】:

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

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: Unable to get property 'onbeforeunload' of undefined or null reference”;

【问题讨论】:

    标签: javascript angularjs unit-testing frontend karma-jasmine


    【解决方案1】:

    为您服务:

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

    【讨论】:

      【解决方案2】:

      你试过了吗:

      $window.trigger('onbeforeunload');
      

      代替:

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

      【讨论】:

        猜你喜欢
        • 2017-04-04
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        相关资源
        最近更新 更多