jameskleeh / angular-confirm

Confirmation modal dialog for AngularJS
Apache License 2.0
150 stars 75 forks source link

Jasmine + Karma + $Confirm #65

Closed Megale closed 8 years ago

Megale commented 8 years ago

Hello,

I'm trying to unit test a delete method that prior to deleting the entity uses $confirm to query the user if he really wants to delete the entity.

Any ideas on how to mock the $confirm?

Cheers

jameskleeh commented 8 years ago

@Megale You would mock it the same way you would mock any other angular factory/service.

Megale commented 8 years ago

Thanks for the quick answer. I'm a bit of a noob in the front end development

The way i'm using $confirm is like this:

`$confirm({ text: 'Are you sure.....' }).then(function() { $scope.removerAjuste(ajuste, marcacao); }); };'

Given your previous answer, i would need to create a mockService that receives a string and returns a promise and then inject it on the constructor of my controller in my unit test replacing the original $confirm?

Cheers

jameskleeh commented 8 years ago

@Megale Yes, however it doesn't take a string, it takes an object; however that shouldn't make any difference. https://www.sitepoint.com/mocking-dependencies-angularjs-tests/

Megale commented 8 years ago

Thank you for the reference, it helped a lot. For future reference, in my scenario i ended up with this:

The mockup in a beforeEach:

$provide.factory('ConfirmMockService', function () {

      return function (texto, setting) {

        return {
          then: function (callback) {

            if (passConfirmMockPromise) {
              callback()
            }

          }
        };
      };
    });
  });

Injecting in a controller:

var confirmMock = $injector.get('ConfirmMockService'); controller('FreqCtrl', { $scope: scope, $window:windowMock, $confirm: confirmMock });

Usage in the app:

$confirm({ text: 'Are you sure '?' }).then(function() { $scope.delete(a, b); });

`