Search code examples
angularjsunit-testingjasmineangularjs-service

How to test function in AngularJS service with mock data


How to create Jasmine unit test for one function in AngularJS service provider. I want to create mock data for myObject and test function getObjectShape() with that mock data as parameter. How to achieve that?

    (function () {
    'use strict';
    angular.module('objectShapes')
            .provider('shapesResolver', shapesResolver);

        function shapesResolver() {

            this.$get = function () {
                return resolver;
            };

            function resolver(myObject) {

                var service = {
                    getObjectShape: getObjectShape
                };

                function getObjectShape() {
                    return myObject.Shape;
                }
            }
        }
})();

Solution

  • Here's a skeleton of a test for your service.

    describe('shapesResolver service', function() {
        var shapesResolver;
    
        beforeEach(module('objectShapes'));
        beforeEach(inject(function(_shapesResolver_) {
            shapesResolver = _shapesResolver_;
        }));
    
        it('should do something, but what?', function() {
            var mockMyObject = {};
    
            shapesResolver(mockMyObject);
    
            // shapesResolver doesn't return anything, and doesn't 
            // have any side effect, so there's nothing to test.
    
            expect(true).toBeTruthy();
        }); 
    });