Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger window.onbeforeunload in jasmine test

Currently, I have created a directive attached to a form. Anytime the form is dirty, I have a confirmation modal by window.onbeforeunload pop up when trying to leave. Right now I'm trying to write a jasmine test to make sure window.onbeforeunload gets called upon refresh/url change.

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';
                }
            };
        }
    };
}]);

Part of the Jasmine Spec

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();
    });
});
like image 854
Tyler Pflueger Avatar asked Nov 15 '14 03:11

Tyler Pflueger


People also ask

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is the difference between Onbeforeunload and Onunload?

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not.

How do you cancel Windows Onbeforeunload?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.


1 Answers

In a unit test it's enough just to test your implementation of the 'onbeforeunload' event. Otherwise you can write e2e test with Protractor.

You can do your test like this:

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..');
  });
});
like image 65
S.Klechkovski Avatar answered Sep 20 '22 19:09

S.Klechkovski