简体   繁体   中英

How do I inject a third party AngularJS module in a unit test?

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

When I try to run this test I get:

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

I have tried to remove all down to very the very basic to rule out other issues. If I change the " FileUploader " variable to FileUploaderX " I get the same error and only the unknown provider name changes, so the problem seem to be within the unit test injection. Also if I change the "beforeEach(module('angularFileUpload'));" to for example "beforeEach(module('angularFileUploadX'));" I get an error that the module could not be found, so the test conf seem to be including the script for the module correctly.

The application works and I'm able to upload a file to my server (not visible here since I removed all logic except for the FileUploader initiation to rule out other issues).

Anyone got any ideas?

Btw, I'm using this module: nervgh/angular-file-upload

Update: I have noticed that if I remove the path to the angularFileUpload module (angular-file-upload.js) in the karma config file It's still the same error that shows, but if I change the module name in the beforeEach (in the test file) it says it can't be found. Could there be a conflict with an existing module with the same name?

 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.

Add the dependency to your karma.config.js file.

ex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM