【问题标题】:How to trigger window.onbeforeunload in jasmine test如何在茉莉花测试中触发window.onbeforeunload
【发布时间】:2014-11-15 03:31:17
【问题描述】:

目前,我创建了一个附加到表单的指令。每当表单变脏时,我都会在尝试离开时弹出 window.onbeforeunload 的确认模式。现在我正在尝试编写一个 jasmine 测试,以确保在刷新/url 更改时调用 window.onbeforeunload。

var app = angular.directive('app');

app.directive('dialog',[$window, function() {
    return {
        restrict: 'A',
        require: 'form',
        link: function(scope, element, attrs, formCtrl) {
            $window.onbeforeunload = function () {
                if(formCtrl.$dirty) {
                    return 'Are you sure you want to leave this form';
                }
            };
        }
    };
}]);

茉莉花规范的一部分

beforeEach(inject(function(_$rootScope_,_$state_,_$window_) {
    $rootScope = _$rootScope_;
    $state = _$state_;
    $window = _$window_;

    spyOn($window, 'onbeforeunload')
}));

describe('Listen for window prompt', function () {
    it('should be called on url/refresh change', function () {
        window.location.reload();
        expect($window.onbeforeunload).toHaveBeenCalled();
    });
});

【问题讨论】:

    标签: angularjs jasmine


    【解决方案1】:

    在单元测试中,只需测试“onbeforeunload”事件的实现就足够了。否则你可以用Protractor编写e2e测试。

    您可以这样进行测试:

    describe('page leave handler', function () {
      it('should handle page leave', function () {
        // given
        var element = compileDirective();
        var formCtrl = element.controller('ngForm');
        formCtrl.$dirty = true;
    
        // when
        var result = $window.onbeforeunload();
    
        // then
        expect(result).toBe('Are you sure..');
      });
    });
    

    【讨论】:

    • 我得到 TypeError: window.onbeforeunload is not a function
    【解决方案2】:

    听起来您正在尝试测试该方法是否执行了它应该执行的操作,这在 url 更改/刷新时会触发。您可能应该测试在此事件中发生的代码。您可以在 jasmine 脚本中使用窗口对象上的 jquery trigger 命令触发此事件:

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

    【讨论】:

    • 当我触发 onbeforeunload 事件时,它会破坏 jasmine 测试并在网页上进行完全刷新。
    猜你喜欢
    • 2022-11-02
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多