jeudi 25 février 2016

How to mock AngularJS $resource with $promise.then in jasmine

I have a a factory which uses Angular resource to make API call. I then created a function called getObjectById and use the factory to query for that object and then modify the object before returning.

Service

            return getObjectById: function(id) {
                return objectFactory.getById({ id: id }).$promise.then(function(response) {
                    return modifyObject(response.object);
                });
            }

I want to test that modifyObject() is working correctly but modifyObject is a private function.

So to test it i'm trying to mock object the response object factory is returning with a spy.

Test

    beforeEach(function() {

    inject(function(objectFactory, $q) {
        spyOn(objectFactory, 'getById').and.returnValue({ $promise: $q.when(readJSON('test/resources/object.json')));
    });
});

But everytime I run the test I get the error

TypeError: Cannot read property 'returnValue' of undefined

If I can get any help on getting it to work that will be great. Even suggestion if i'm doing the layout wrong.

Aucun commentaire:

Enregistrer un commentaire