I have a directive that look like this:
angular.directive('myDirective', ['$compile','$timeout', function($compile,$timeout){
console.log("myDirective compile");
return {
link: function(scope, element) {
console.log("myDirective before timeout");
$timeout(function(){
console.log("myDirective after timeout");
});
}
};
}]);
When I do unit test with Karma-Jasmine, I get the LOG
output of myDirective compile
and myDirective before timeout
. But no output for myDirective after timeout
How can I get the $timeout
function to run in unit test?
You can use the flush
method on the $timeout
service to flush the timeouts that you set. https://docs.angularjs.org/api/ngMock/service/$timeout
Note that this is available in ngMock and you therefore need to include angular-mocks. (I'm fairly sure you have but just in case.)
See the test below for an example.
describe('my directive test', function () {
var element;
var scope;
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope){
element = '<my-directive></my-directive>';
scope = $rootScope.$new();
element = $compile(element)(scope);
scope.$digest();
spyOn(console, 'log').and.callThrough();
}));
it('should not log the timeout', inject(function ($timeout) {
expect(console.log).not.toHaveBeenCalledWith('myDirective after timeout');
}));
it('should log after timeout', inject(function ($timeout) {
$timeout.flush();
expect(console.log).toHaveBeenCalledWith('myDirective after timeout');
}));
});
Use
$timeout.flush(amount)
In your tests, with amount
the amount of time you want to pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With