[英]Unit Testing a AngularJS service?
嘿,我的测试服务需要帮助。
我有此服务: 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。 我确实测试过类似的东西,但是它说无法读取编码为1的属性:
'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"));
});
});
});
我希望有人可以告诉我我做错了什么?
您没有调用函数对值进行编码,请尝试:
it('should output: ', function() {
scope.numberToEncode = "123";
scope.encode1();
expect(scope.encoded1.toBe("00050221F3"));
});
但是,这不是我们应该对服务进行单元测试的方式。 为了对服务进行单元测试,我们将分别测试服务的每个功能。
这种验证scope.encode1
功能的测试也不正确。 我们应该模拟FnEncode
并验证是否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
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.