How to run window.onbeforeunload in jasmine tests

Currently, I have created a directive attached to the form. Anytime a form is dirty, I have a confirmation of the modality of window.onbeforeunload when you try to leave. Right now I'm trying to write a jasmine test to make sure window.onbeforeunload gets a call when updating / changing the URL.

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 specification

 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(); }); }); 
+6
source share
2 answers

It looks like you are trying to check if a method does what it should do, it fires when the URL has changed / updated. You will probably have to test the code that happens inside this event. You can fire this event in your jasmine script using the jquery trigger command on the window object, so something like this.

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

+1
source

In unit test, just checking your implementation of the onbeforeunload event is enough. Otherwise, you can write e2e test using Protractor .

You can do your test as follows:

 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..'); }); }); 
+1
source

Source: https://habr.com/ru/post/978223/


All Articles