如何使用模拟数据测试AngularJS服务中的函数

时间:2015-04-23 06:01:50

标签: angularjs unit-testing jasmine angularjs-service

如何在AngularJS服务提供程序中为一个函数创建Jasmine单元测试。我想为myObject和测试函数getObjectShape()创建模拟数据,并将该模拟数据作为参数。怎么实现呢?

    (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;
                }
            }
        }
})();

1 个答案:

答案 0 :(得分:2)

以下是您服务测试的框架。

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();
    }); 
});