单元测试:Karma-Jasmine不解析Promise而不隐式调用$ rootScope。$ digest();

时间:2017-03-07 11:45:50

标签: javascript angularjs unit-testing jasmine karma-jasmine

我有一个Angular服务,可以调用服务器并获取用户列表。该服务返回Promise

问题

除非我在服务或测试本身中调用$rootScope.$digest();,否则

Promise不会得到解决。

    setTimeout(function () {
        rootScope.$digest();
    }, 5000);

显然,调用$rootScope.$digest();是一种解决方法,我无法在角度服务中调用它,因此我在unit test中以5秒的间隔调用它,我认为这是一种不好的做法。 / p>

请求

请为此提出实际解决方案。

以下是我所写的测试。

   // Before each test set our injected Users factory (_Users_) to our local Users variable
    beforeEach(inject(function (_Users_, $rootScope) {
        Users = _Users_;
        rootScope = $rootScope;
    }));

    /// test getUserAsync function
    describe('getting user list async', function () {

        // A simple test to verify the method getUserAsync exists
        it('should exist', function () {
            expect(Users.getUserAsync).toBeDefined();
        });


        // A test to verify that calling getUserAsync() returns the array of users we hard-coded above
        it('should return a list of users async', function (done) {
            Users.getUserAsync().then(function (data) {
                expect(data).toEqual(userList);
                done();
            }, function (error) {
                expect(error).toEqual(null);
                console.log(error.statusText);
                done();
            });

            ///WORK AROUND
            setTimeout(function () {
                rootScope.$digest();
            }, 5000);
        });
    })

服务

  Users.getUserAsync = function () {
    var defered = $q.defer();

    $http({
      method: 'GET',
      url: baseUrl + '/users'
    }).then(function (response) {
      defered.resolve(response);
    }, function (response) {
      defered.reject(response);
    });

    return defered.promise;
  }

1 个答案:

答案 0 :(得分:0)

您可以通过拨打$timeout.flush()来兑现承诺。它使您的测试更加同步。

以下是一个例子:

   it('should return a list of users async', function (done) {
        Users.getUserAsync().then(function (data) {
            expect(data).toEqual(userList);
            done();
        }, function (error) {
            expect(error).toEqual(null);
            console.log(error.statusText);
            done();
        });

        $timeout.flush();
    });

除此之外:故障回复不会被处理,因此会增加测试的复杂性。