【问题标题】:AngularJS - Unit Test with $timeoutAngularJS - 带有 $timeout 的单元测试
【发布时间】:2015-04-07 09:23:42
【问题描述】:

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

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 函数在单元测试中运行?

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

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

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

    请参阅下面的测试以获取示例。

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

    【讨论】:

      【解决方案2】:

      使用

      $timeout.flush(amount)
      

      在您的测试中,amount 是您想要通过的时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-25
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        • 2013-05-27
        • 2015-09-13
        • 1970-01-01
        • 2018-07-06
        相关资源
        最近更新 更多