簡體   English   中英

茉莉在角度1.5控制器中測試模擬服務

[英]jasmine testing a mock service in an angular 1.5 controller

給出以下測試。
我如何確保兌現承諾並提供數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM