我想测试 $interval 的回调函数是否在一定时间间隔后被调用。但我得到的参数列表是空的。我不知道为什么。
下面是包含 $interval 的代码 -
(function() {
"use strict";
var app = angular.module("AppModule");
app.controller("cntrl", cntrl);
/*@ngInject*/
function cntrl($scope, $state, $interval, utils) {
var vm = this,
data,
timer,
i;
init();
function init() {
_createList();
}
/*Refreshing list after each 30 second interval*/
timer = $interval(function() {
utils.getObjectList()
.then(function(data) {
utils.data = data;
});
init();
}, 1000);
/*Cancelling interval when scope is destroy*/
$scope.$on('$destroy', function() {
$interval.cancel(timer);
});
function _createList() {
//some code
}
}
})();
下面是它的单元测试 -
describe.only("Unit Controller: cntrl", function() {
"use strict";
// Angular injectables
var $q, $httpBackend, $injector, $controller, $rootScope, $state, $location, $templateCache, $compile, $interval;
// Module defined (non-Angular) injectables
var $scope;
// Local variables used for testing
var vm;
// Initialize modules
beforeEach(function() {
module("AppModule");
});
beforeEach(function() {
var templateHtml;
inject(function(_$q_, _$controller_, _$rootScope_, _$state_, _$location_, _$templateCache_, _$compile_, _$interval_) {
$q = _$q_;
$controller = _$controller_;
$rootScope = _$rootScope_;
$location = _$location_;
$state = _$state_;
$templateCache = _$templateCache_;
$compile = _$compile_;
$interval = _$interval_;
$scope = $rootScope.$new();
templateHtml = $templateCache.get("/modules/list.html");
$compile(templateHtml)($scope);
});
});
beforeEach(function() {
vm = $controller("cntrl", {
$scope: $scope
});
});
it("Should call the list API continuosly after a certain interval", function() {
var fn = function() {
utils.getObjectList()
.then(function(data) {
utils.data = data;
});
init();
};
var clock = sinon.useFakeTimers();
var mySpy = sinon.spy($interval);
var throttled = throttle(mySpy);
throttled();
clock.tick(999);
console.log(mySpy);
expect(mySpy.notCalled).to.be.true;
clock.tick(1);
expect(mySpy.called).to.be.true;
expect(intervalSpy.calledWith(fn)).to.be.true; //This is failing
console.log(intervalSpy.getCall(0).args); //this shows empty.
function throttle(callback) {
var timer;
return function() {
clearTimeout(timer);
var args = [].slice.call(arguments);
timer = setTimeout(function() {
callback.apply(this, args);
}, 1000);
};
}
});
});