茉莉花在角度1.5控制器中测试模拟服务

时间:2017-03-18 13:09:57

标签: javascript angularjs jasmine

鉴于以下测试 如何确保承诺得到解决,数据提供

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;
}());

...

1 个答案:

答案 0 :(得分:0)

首先,你可以使用$ 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);