AngularJS - $ timeout的单元测试

use*_*781 4 unit-testing jasmine angularjs karma-jasmine

我的指令看起来像这样:

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");
            });
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

当我用Karma-Jasmine进行单元测试时,我得到了和的LOG输出.但没有输出myDirective compilemyDirective before timeoutmyDirective after timeout

如何$timeout在单元测试中运行该功能?

Mar*_*lak 12

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

请注意,这在ngMock中可用,因此您需要包含角度模拟.(我很确定你有,但以防万一.)

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

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');
    }));
});
Run Code Online (Sandbox Code Playgroud)


Pet*_*ell 5

$timeout.flush(amount)
Run Code Online (Sandbox Code Playgroud)

在你的测试中,amount你想通过多少时间。