2
votes

I'm having some issues testing functions return promises in the Jasmine. This solution is very close to the issue that i'm having: How to resolve promises in AngularJS, Jasmine 2.0 when there is no $scope to force a digest?

The post is from 2014 and it's not clear what version of jasmine they are using. Is this still the correct why to test a function that resolves a promise in the current (2.4.0^) version?

Edit:

I have a service whose pattern looks something like this:

angular.module('somemodule').factory('listOfDependencies','NewService');
function NewService(listOfDependencies){
    var getObject = function(para1, para2,...,paraN){
    var deferred = $q.defer();
    if(someDependency.method())
        deferred.resolve(someDependency.get(key));
    else
        deferred.resolve(returnsNewObject);
    // there's also a case that returns deferred.reject(reason);
    return deferred.promise;
    };
    return getObject:getObject;
    };

In my spec, the test currently looks something like this

        it('should return the object', inject(function() {
            var obj = { some: Object };
            NewService.getObject('param1'...'paramN').then(
            function(data){
                 expect(data.obj).toEqual(obj);
            },
            function(response){
                //promise failed
          });                        

Now what I expect to be returned based on the object 'obj' should pass. In my service it's this case it should logically return"

if(someDependency.method())
        deferred.resolve(someDependency.get(key));

The problem is that is that the object it returns is:

        else
        deferred.resolve(returnsNewObject);

There's nothing wrong the the logic in the code or any its dependencies (I pulled all of this apart and tested it many time) so I feel like something is wrong in my syntax(?) in the jasmine spec or i'm just not testing the promise correctly. Thanks for taking a look at this!

2
Please do post a little code to elaborate - this isn't clear.Benjamin Gruenbaum
Of course! Let me know if you need anything else, I just wasn't in front of my code when I posted.arturobelano

2 Answers

0
votes

Resolving the promise and then checking that the values it resolves to are valid and expected are definitely one way of doing it.

If you're ok with using the Chai library, it's a lot more concise: http://chaijs.com/plugins/chai-as-promised/

To make your code easier to unit test, try doing as much of the heavy lifting as possible in Angular services (as opposed to in the controllers), and have the services return promises. That way your unit tests can call the service methods with various inputs and ensure the promises are rejected/resolved as expected.

0
votes

I resolved this issue by calling $rootScope.$apply(); at the end of my test.