2016-06-17 79 views
0

uploadCtrl.js如何在單元測試中注入第三方AngularJS模塊?

'use strict'; 
angular.module('app.controllers').controller('UploadCtrl', ['$scope', 'FileUploader', 
    function ($scope, FileUploader) { 
     $scope.uploader = new FileUploader(); 
     $scope.upload = function() { 
      // Do some validation of form fields before submitting to server here... 
      $scope.success = true; 
     }; 
    }] 
); 

uploadCtrlSpec.js

'use strict'; 
describe('UploadCtrl', function() { 
    var scope, controller, FileUploader, UploadCtrl; 
    beforeEach(module('app.controllers')); 
    beforeEach(module('angularFileUpload')); 
    beforeEach(inject(function (_FileUploader_, $rootScope, $controller) { 
     scope = $rootScope.$new(); 
     FileUploader = _FileUploader_; 
     controller = $controller; 

     UploadCtrl = controller('UploadCtrl', {$scope: scope, FileUploader: FileUploader}); 
    })); 

    it('verify upload success', function() { 
     scope.upload(); 
     expect(scope.success).toBeTruthy(); 
    }); 
}); 

當我嘗試運行這個測試,我得到:

Error: [$injector:unpr] Unknown provider: FileUploaderProvider <- FileUploader 

我已經嘗試了所有的去除下來非常非常基本排除其他問題。如果我將「FileUploader」變量改爲FileUploaderX「我得到相同的錯誤,並且只有未知的提供程序名稱發生更改,所以問題似乎在單元測試注入中 另外,如果更改」beforeEach(module ('angularFileUpload'));「to例如」beforeEach(module('angularFileUploadX'));「我得到一個錯誤,模塊找不到,所以測試conf似乎包括正確的模塊腳本。

應用程序的工作,我能夠將文件上傳到我的服務器(在此不可見,因爲我刪除除FileUploader啓動以排除其他問題的所有邏輯)。

任何人有任何想法?

順便說一句,我使用這個模塊: nervgh/angular-file-upload

更新:我注意到,如果我刪除路徑angularFileUpload模塊(角文件upload.js)在業力配置文件它仍然顯示相同的錯誤,但是如果我在beforeEach(在測試文件中)中更改模塊名稱,則表示找不到它。與現有的同名模塊有衝突嗎?

Error: [$injector:modulerr] Failed to instantiate module angularFileUploadX due to: 
    Error: [$injector:nomod] Module 'angularFileUploadX' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. 

回答

0

將依賴關係添加到您的karma.config.js文件。

例如:

{ 
    files: [ 
     "path/to/FileUploader.js", 
     ... 
    ], 
    ... 
} 
+0

我在問題中提到:「所以測試的conf似乎是包括腳本正確的模塊」,所以它不應該是。我在配置文件中包含https://github.com/nervgh/angular-file-upload/blob/master/dist/angular-file-upload.js(angular-file-upload.js),但它是ofcourse本地存儲在項目文件夾結構中。或者我錯過了什麼? – KungWaz

相關問題