如何在单元测试中注入第三方AngularJS模块?

时间:2016-06-17 14:47:54

标签: javascript angularjs unit-testing jasmine

uploadCtrl.js

'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'));”例如“beforeEach(module('angularFileUploadX'));”我收到一个错误,找不到模块,因此测试配置似乎正确地包含了模块的脚本。

应用程序正常运行,我可以将文件上传到我的服务器(这里不可见,因为除了FileUploader启动之外我删除了所有逻辑以排除其他问题)。

有人有任何想法吗?

顺便说一下,我正在使用这个模块: nervgh/angular-file-upload

更新:我注意到如果我在karma配置文件中删除angularFileUpload模块(angular-file-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.

1 个答案:

答案 0 :(得分:0)

将依赖项添加到karma.config.js文件中。

例如:

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