Jasmine 在 Angular 1.5 控制器中测试模拟服务



给定以下测试。
如何确保承诺已解决并提供数据。

describe("component: FicaStatusComponent",
    function () {
        var fs;
        beforeEach(function () {
            module("aureus",
                function ($provide) {
                    $provide.service("ficaService", function () {
                        this.status = function () {
                            return $q(function (resolve, reject) {
                                resolve([{ documentType: { id: 1 } }]);
                            });
                        }
                    })
                });
        });
        beforeEach(inject(function (_$componentController_, _ficaService_) {
            $componentController = _$componentController_;
            fs = _ficaService_;
        }));
        it("should expose a `fica` object", function () {
            console.log('should expose');
            var bindings = {};
            var ctrl = $componentController("ficaStatus", null, bindings);
            expect(ctrl.fica).toBeDefined();
        });
        it("compliant with no documents should not be compliant",
            function () {
                var ctrl = $componentController("ficaStatus");
                expect(ctrl.fica.length).toEqual(1);
            });
    }
);

第二个测试不符合任何文档...失败。长度为零。另一个测试正在通过,所以我有正确的控制器被实例化,属性已定义。

模拟服务未正确解析数据,可能是因为Promise仍在执行,或者根本没有被调用。

下面是组件控制器的实现:

var FicaStatusController = (function () {
    function FicaStatusController($log, $loc, ficaService) {
        var _this = this;
        this.$log = $log;
        this.$loc = $loc;
        this.ficaService = ficaService;
        this.fica = [];
        this.ficaService.status(1234).then(function (_) { return _this.fica = _; });
    }

服务如下:

var FicaStatusService = (function () {
    function FicaStatusService($log, $http) {
        this.$log = $log;
        this.$http = $http;
    }
    FicaStatusService.prototype.status = function (accountNumber) {
        var url = "api/fica/status/" + accountNumber;
        this.$log.log("status: " + url);
        return this.$http
            .get(url)
            .then(function (_) { return _.data; });
    };
    return FicaStatusService;
}());
...

首先,您可以使用如下$q:

this.status = function () {
    return $q.when([{ documentType: { id: 1 } }]);
}

其次,要解决承诺使用$scope.$digest、$rootScope.$digest:

var a = $q.when({test: 1});
expect(a.test === 1).toBe(false);
$rootScope.$digest();
expect(a.test === 1).toBe(true);

最新更新