16

以下测试一直失败,我不知道为什么?我想弄清楚如何用 Jasmine 测试延迟/承诺。

错误

Expected undefined to be 'Resolved Data'.

测试

    describe('Queued Repository', function () {
    var ctrl,
        rootScope,
        scope,
        service;

    beforeEach(function () {
        module('testApp');

        inject(function ($rootScope, $controller, TestSrvc) {
            rootScope = $rootScope;
            scope = $rootScope.$new();
            service = TestSrvc;
        });
    });

    afterEach(inject(function ($rootScope) {
        $rootScope.$apply();
    }));

    it('test something', function () {
        expect(service.calculate(1, 5)).toBe(6);
    });

    it('resolves promises', function () {
        var result;

        service.getPromise().then(function (data) {
            result = data;
        });

        rootScope.$apply();
        expect(result).toBe('Resolved Data');
    });
});

服务

    var app = angular.module('testApp', []);

app.service('TestSrvc', ['$q', '$timeout', '$http', function ($q, $timeout, $http) {
    return {
        getPromise: function () {
            var d = $q.defer();

            $timeout(function () {
                d.resolve('Defered Result');
            }, 5000);

            return d.promise;
        },
        getSomething: function () {
            return "Test";
        },
        calculate: function (x, y) {
            return x + y;
        }
    }
}]);
4

2 回答 2

9

尝试调用$timeout.flush()之前expect(result).toBe('Resolved Data');

于 2013-10-31T23:51:32.337 回答
3

在您的示例中,您将需要同时调用$timeout.flush()AND $rootScope.$apply()

说明:$timeout.flush()将强制您$timeout的服务立即运行。然后,您的服务将调用 ' resolve' - 但promise.then()直到下一个摘要周期才会调用;因此,您将需要调用$rootScope.$apply()以传播任何“解决”和“监视” - 这将同步发生。

NOTE:在 Jasmine 中,确保您的promise.then()函数出现BEFORE在您的调用中,$rootScope.$apply否则它不会触发该promise.then()函数。(我还没弄清楚为什么 Jasmine 会出现这种情况。)

于 2014-11-10T23:47:33.327 回答