8

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?

2 Answers 2

16

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');
    }));
});
Sign up to request clarification or add additional context in comments.

Comments

5

Use

$timeout.flush(amount)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.