簡體   English   中英

如何:模擬模塊依賴項

[英]How to: mock module dependencies

撕下我的頭發。

我有以下要測試的模塊/控制器

angular
    .module('monitor.tableLord.controller', ['monitor.wunderTable'])
    .controller('TableLordController', TableLordController);

    TableLordController.$inject = ['$scope', 'historyState'];
    function TableLordController($scope, historyState) {
        ....some code....
    }

monitor.wunderTable模塊包含應在控制器之前加載的指令,但是我要測試的控制器實際上並不依賴於monitor.wunderTable。 monitor.wunderTable確實還有很多其他依賴項。

我的測試文件:

describe('TableLordController', function() {
    var $scope, historyState;

    beforeEach(function() {
        angular.module('monitor.wunderTable', []);
        module('monitor.tableLord.controller');
    });

    beforeEach(angular.mock.inject(function($rootScope, $controller) {
            $scope = $rootScope.$new();
            $controller('TableLordController', {$scope: $scope, historyState: {}});
    }));

    it('loads', function() {
        $scope.$digest();
    });
});

由於某種原因(我認為這不可能),我的模擬版本Monitor.wunderTable干擾了我對該模塊的測試。 現在,此模塊中定義的控制器的所有測試都會失敗,並顯示:“參數'WunderTableController'不是函數,未定義”。

我認為這是相關的,這是我對monitor.wunderTable的定義:

angular
    .module('monitor.wunderTable', [
        'ui.grid',
        'ui.grid.infiniteScroll',
        'ui.grid.autoResize',
        'monitor.wunderTable.service'
     ])
    .controller('WunderTableController', WunderTableController)
    .directive('wunderTable', wunderTable);

function wunderTable(){...}
WunderTableController.$inject = [];
function WunderTableController(...){...}

編輯:暗示我刪除模塊依賴項的帖子(因為不是嚴格需要的)將不被接受為正確答案(並且可能被低估)。

您的困惑來自對模塊在Angular中的工作方式的誤解。 模塊存儲在angular 一旦覆蓋它們,它們將被當前測試運行覆蓋,而不是被當前規范覆蓋。 ngMock不支持模塊模擬(這需要在Angular核心中進行一些實質性更改),而beforeEach將無濟於事。

除非您要在單獨的運行中運行測試套件,否則解決方案是在對模塊進行模擬之前對其進行備份。 在某些情況下, angular.extendangular.copy無法正確處理復雜的對象。 Object.assignjQuery.extendnode-extend可能是更好的選擇。 extend的情況下,如有必要,也可以使用深層復制。

所以在一個測試套件中

var moduleBackup = angular.module('monitor.wunderTable');
angular.module('monitor.wunderTable', []);

describe('TableLordController', function() {
    ...

而在另一個

Object.assign(angular.module('monitor.wunderTable'), moduleBackup);

describe('WunderTableController', function() {
    ...

TDD的優點在於,它可以清楚地指出應用程序設計中的缺陷,並教會開發人員以立即無情的方式編寫易於測試的代碼。 模塊依賴性意味着模塊內部的組件依賴於另一個組件。 如果沒有,或者耦合太緊密,則可以認為這是潛在的缺陷,是重構的主題。

該解決方案容易被破解並且容易崩潰的事實使其不適合測試。

TL; DR:是的,您必須刪除模塊依賴性。

暫無
暫無

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

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