Javascript.confirm() and Angularjs Karma e2e test

mrt picture mrt · May 7, 2013 · Viewed 13.8k times · Source

I have an Angularjs application that uses simple javascript confirm before executing some actions.

Controller:

function TokenController($scope) {
  $scope.token = 'sampleToken';

  $scope.newToken = function() {
    if (confirm("Are you sure you want to change the token?") == true) {
      $scope.token = 'modifiedToken';
    }
  };
}

View:

<div id="tokenDiv">
  Token:{{token}} <button ng-click="newToken()">New Token</button>
</div>

Now I want to have an end to end test to check the token is being replaced correctly in the view. How can I intercept the javascript.confirm() call so it doesn't stop the execution of the test?

Test:

it('should be able to generate new token', function () {
   var oldValues = element('#tokenDiv').text();
   element('button[ng-click="newToken()"]').click(); // Here the javascript confirm box pops up.
   expect(element('#tokenDiv').text()).not.toBe(oldValues);
});

So far I've tried to redefine the window.confirm function but then the actual call complains that it is undefined.

I also wanted to set up a Jasmine spy on window.confirm but in the following syntax spyOn(window, 'confirm'); it gives me an error saying you can not spy on null.

How would I go about making such test work?

Answer

Andrei V picture Andrei V · Aug 29, 2014

Another option would be to directly create a spy and automatically return true:

//Jasmine 2.0
spyOn(window, 'confirm').and.callFake(function () {
     return true;
});

//Jasmine 1.3
spyOn(window, 'confirm').andCallFake(function () {
     return true;
});