AngularJS - 带 $timeout 的单元测试

AngularJS - Unit Test with $timeout

我有一个如下所示的指令:

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");
            });
        }
    };
}]);

当我使用 Karma-Jasmine 进行单元测试时,我得到 myDirective compilemyDirective before timeoutLOG 输出。但是 myDirective after timeout

没有输出

如何在单元测试中将 $timeout 函数设置为 运行?

使用

$timeout.flush(amount)

在您的测试中,amount 您希望通过的时间。

您可以在 $timeout 服务上使用 flush 方法来刷新您设置的超时。 https://docs.angularjs.org/api/ngMock/service/$timeout

请注意,这在 ngMock 中可用,因此您需要包含 angular-mock。 (我很确定你有,但以防万一。)

查看下面的测试示例。

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');
    }));
});