单元测试AngularJS服务?

时间:2014-04-14 11:23:00

标签: javascript angularjs unit-testing service karma-runner

嘿,我的测试服务需要帮助。

我有这项服务: MyService.js

这个控制器:

angular.module('MyControllers', [])

.controller('MyCtrl2', ['$scope', 'FnEncode', function ($scope, FnEncode) {

        $scope.encoded1 = "";
        $scope.encoded2 = "";
        $scope.encoded3 = "";

        $scope.encode1 = function() {
            $scope.encoded1 = FnEncode.encodeUUI(FnEncode.encodeFunctionalNumber($scope.numberToEncode));
        };

        $scope.encode2 = function() {
            $scope.encoded2 = FnEncode.encodeUUI(FnEncode.encodeFunctionalNumber($scope.numberToEncode)+
                FnEncode.encode2($scope.EncodeWith2));
        };

        $scope.encode3 = function() {
            $scope.encoded3 = FnEncode.encodeUUI(FnEncode.encodeFunctionalNumber($scope.numberToEncode)+
                FnEncode.encode3($scope.EncodeWith3));
        };
    }]);

当我在文本字段中输入123时,服务基本上就是输出它输出00050221F3,其中第一个00是encodeUUI。 我测试了类似的东西,但它说无法读取属性encoded1:

'use strict';

describe('My services', function() {

    beforeEach(module('myApp'));

    beforeEach(module('MyServices'));

    describe('MyCtrl2', function() {

       var scope, ctrl;
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            ctrl = $controller('MyCtrl2', {$scope: scope});
        }));

        it('should output: ', function(scope) {
            expect(scope.encoded1.toBe("00050221F3"));     
        });
    });
});

我希望有人可以告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

您没有调用函数对值进行编码,请尝试:

it('should output: ', function() {
     scope.numberToEncode = "123";
     scope.encode1();
     expect(scope.encoded1.toBe("00050221F3"));     
});

但是,这不是我们应该如何对服务进行单元测试。为了对服务进行单元测试,我们分别测试服务的每个功能。

这种验证scope.encode1功能的测试也不正确。我们应该模拟FnEncode并验证FnEncode的函数是否按预期顺序调用。

要测试您的服务,您应该执行以下操作:

'use strict';

describe('My services', function() {

    beforeEach(module('myApp'));

    beforeEach(module('MyServices'));

    describe('MyCtrl2', function() {

        var encode;
        beforeEach(inject(function(FnEncode) {
            encode = FnEncode; //inject your service and store it in a variable
        }));

        //Write test for each of the service's functions

        it('encode Functional Number: ', function() {
            var encodedValue = encode.encodeFunctionalNumber("123");
            expect(encodedValue).toBe("00050221F3");  //replace 00050221F3 with your expected value
        });

        it('encode UUI: ', function() {
            var encodedValue = encode.encodeUUI("123");
            expect(encodedValue).toBe("00050221F3");  //replace 00050221F3 with your expected value
        });
    });
});