簡體   English   中英

在茉莉花中模擬$ q.all for AngularJS控制器

[英]Mocking $q.all in jasmine for angularjs controller

我正在為角度控制器編寫茉莉花測試用例,這些用例具有一個具有一系列應解決的承諾的init函數:

    (function () {
    angular.controller("xyz", ['$scope', "Utility", "Api",
        function ($scope, Utility, Api) {
            var locals = $scope.locals = {
                id: 1,
                amount: 2,
                products: 3
            };
            function init() {
                locals.busyPromise = Utility.resolveAll(
                    {
                        name: 'a',
                        promise: Api.get,
                        then: function (response) { locals.id = 2; }
                    },
                    {
                        name: 'b',
                        promise: Api.find,
                        then: function (response) { locals.amount = 4; }
                    }
                ).then(function (response) { locals.products = 6; });
            }
           init();
        }
    ])
})();

Utility是一個外部腳本,用於解析數組中的每個promise,並執行它們的then函數以設置本地屬性。 數組中的所有promise解析后,它將移至resolveAll函數並執行它。

我的問題是,當在Jasmine中注入依賴項時,我們如何模擬Utility.resolveAll。 就我而言,無論我嘗試什么,它都永遠不會進入單個promise的then塊,而直接進入resolveAll的then塊。

在這里我會做什么:

首先,如果有的話,請模擬UtilityApi服務

  let Utility, Api;
  beforeEach(() => {
    Utility = jasmine.createSpyObj('Utility', ['resolveAll']);
    Api = jasmine.createSpyObj('Api', ['find', 'get']);
  });

然后在測試中:

it('should test component startup', function() {
       let resolveObjects;

       Utility.resolveAll.and.callFake(function(...args) {
         resolveObjects = args; // save all arguments, passed to `resolveAll` method

         return $q.when();
       })

       $scope = $rootScope.$new();
       let controller = $controller('xyz', {$scope, Utility, Api});
       $rootScope.digest(); // resolve $q.when so you can test overall promise

       expect($scope.locals.products).toBe(6); // test overall promise

       // now, test all the arguments

       // 0
       expect(resolveObjects[0].name).toBe('a');

       resolveObjects[0].promise();
       expect(Api.get).toHaveBeenCalledTimes(1);

       resolveObjects[0].then();
       expect($scope.locals.id).toBe(4); 

       // 1
       expect(resolveObjects[1.name).toBe('b');

       resolveObjects[1].promise();
       expect(Api.find).toHaveBeenCalledTimes(1);

       resolveObjects[1].then();
       expect($scope.locals.products).toBe(4); 
});

暫無
暫無

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

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