1

I want to mock a service for unit test in angularjs which looks something like this:

 TranslationService.translate(args)
                                    .then(function translated(value) {
                                        //somecode
                                        return;
                                    })
                                    .catch()
                                    .done();

Following this answer: How do I mock a service that returns promise in Angularjs Jasmine unit test?

This is what I did to mock it :

    TranslateServiceMock = {
        translate: jasmine.createSpy('translate').and.callFake(function() {
            var deferred = $q.defer();
            deferred.resolve('Remote call result');
            return deferred.promise;
    })};

But seems like this still doesn't work, I am guessing its because of the chained 'done' and 'catch'methods,

This is the error I get:

TypeError: undefined is not a constructor (near '....done();...'

Running out of ideas why this might be happening or how to fix this..

Snedden27
  • 1,870
  • 7
  • 32
  • 60
  • 3
    The `.done` method is not part of [the Promise API](https://docs.angularjs.org/api/ng/service/$q#the-promise-api). – georgeawg May 01 '19 at 17:45

1 Answers1

0

As mentioned in the comments, done is not a part of promise object.

I got this working by stubbing the done callback :

beforeEach(  function () {
    module(myModule.name, function ($provide) {
        // define a .done on the $q Promise
        $provide.decorator('$q', function ($delegate) {
            var Promise = $delegate.when().constructor;
            Promise.prototype.done = angular.noop;
            return $delegate;
        });

        $provide.factory('TranslationService', function ($q) {
            var svc = jasmine.createSpyObj('TranslationService', ['translate']);

            svc.translate.and.returnValue($q.when(''));

            return svc;
        });
    });
});
Snedden27
  • 1,870
  • 7
  • 32
  • 60