Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Unit Test with $timeout

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?

like image 757
user1995781 Avatar asked Apr 07 '15 09:04

user1995781


2 Answers

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');
    }));
});
like image 142
Mark Polak Avatar answered Oct 11 '22 22:10

Mark Polak


Use

$timeout.flush(amount)

In your tests, with amount the amount of time you want to pass.

like image 27
Peter Ashwell Avatar answered Oct 11 '22 21:10

Peter Ashwell