Unit Testing Angular Service that uses $timeout with Jasmine's Mock Clock

后端 未结 2 1046
情话喂你
情话喂你 2020-12-29 18:18

I have a function inside one of my angular services that I\'d like to be called repeatedly at a regular interval. I\'d like to do this using $timeout. It looks something l

相关标签:
2条回答
  • 2020-12-29 19:05

    Do not make your test Async by using Jasmine's clock. Instead, use $timeout.flush() to synchronously maintain the flow of the test. It may be a bit tricky to setup, but once you get it then your tests will be faster and more controlled.

    Here's an example of a test that does it using this approach: https://github.com/angular/angular.js/blob/master/test/ngAnimate/animateSpec.js#L618

    0 讨论(0)
  • 2020-12-29 19:20

    @matsko's answer led me down the right path. I thought I'd post my "complete" solution to make it simpler to find the answer.

    The thing to test

    angular.module("app").service("MyService", function() {
        return {
            methodThatHasTimeoutAndReturnsAPromise: function($q, $timeout) {
                var deferred = $q.defer();
                $timeout(function() {
                    deferred.resolve(5);
                }, 2000);
                return deferred.promise;
            }
        };
    });
    

    The test

    describe("MyService", function() {
        var target,
            $timeout;
        beforeEach(inject(function(_$timeout_, MyService) {
            $timeout = _$timeout_;
            target = MyService;
        }));
        beforeEach(function(done) {
            done();
        });
        it("equals 5", function(done) {
            target.methodThatHasTimeoutAndReturnsAPromise().then(function(value) {
                expect(value).toBe(5);
                done();
            });
            $timeout.flush();
        });
    });
    
    0 讨论(0)
提交回复
热议问题