我有一个用 angularJS 编写的小控制器。
第一个函数实际上是调用第二个函数来执行计算并将其返回。
我想在我的测试中模拟第二个函数,以便它返回我在模拟中提供的值,而不是调用该函数。
var app = angular.module('mathModule', []);
app.controller('mathService', ['$scope', function($scope){
$scope.first = 0;
$scope.second = 0;
$scope.addTwoNumbers = function(x, y) {
return x + y;
};
$scope.callAddFunction = function() {
return $scope.addTwoNumbers(10, 20);
}
}]);
require('./mathService.js');
describe('Math service', function() {
beforeEach(
angular.mock.module('mathModule')
);
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
describe('Test using 2 numbers', function() {
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('mathService', { $scope: $scope });
});
it("Nested function", function() {
var total = $scope.callAddFunction();
expect(total).toEqual(31);
});
});
});
在这里我想模拟 addTwoNumbers()
,这样我们就不会调用我们在测试期间提供的值。
类似于 Mock(addTwoNumbers(x,y)) = 0
,所以现在 callAddFunction 将返回 0 而不是 30,如果没有模拟它应该返回。