我有一个递归方法,如果设置了一个标志,它将每五秒调用一次。我试图编写一个测试间谍方法,调用它,等待六秒然后期望该方法被调用两次的测试。我的测试失败,因为间谍报告该方法只被调用一次(初始调用)。
我正在使用Angular style guide,因此请将这些方法附加到this
的占位符。我怀疑从角度模拟$controller()
返回的控制器的作用域可能存在问题,但我不确定 - 大多数人都在将方法附加到$scope
。
如果不将方法附加到$scope
,如何创建间谍来验证我的方法是否已被调用两次?
app.js:
'use strict';
angular
.module('MyApp', [
//...
]);
angular
.module('MyApp')
.controller('MyController', MyController);
MyController.$inject = [
//...
];
function MyController() {
var vm = this;
vm.callMyself = callMyself;
vm.flag = false;
function callMyself () {
console.log('callMyself');
if (vm.flag) {
console.log('callMyself & flag');
setTimeout(vm.callMyself, 5000);
}
}
}
appSpec.js:
describe('MyController', function () {
var $scope;
beforeEach(function () {
module('MyApp');
});
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
controllerInstance = $controller('MyController', {$scope: $scope});
}));
it('should call itself within 6 seconds if flag is true', function (done) {
controllerInstance.flag = true;
spyOn(controllerInstance, 'callMyself');
controllerInstance.callMyself();
setTimeout(function () {
expect(controllerInstance.callMyself).toHaveBeenCalledTimes(2);
done();
}, 6000);
}, 7000);
});
答案 0 :(得分:4)
您需要使用.and.callThrough()
来进一步执行自称的函数:
通过将间谍与
and.callThrough
联系起来,间谍仍会跟踪对它的所有调用,但此外它还会委托给实际的实现。
spyOn(controllerInstance, 'callMyself').and.callThrough();
在弹药中测试 - 它有效。