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();
});
});
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.
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.
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.
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..');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With