SilentDev
SilentDev

Reputation: 22747

How to correctly inject a factory using Jasmine / karma and test it?

This is my factory / base.js:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {

And this is my test_base.js:

describe('Factory: BaseService', function() {
    var fctry, mockBackend;

    beforeEach(function() {

        module('BaseApp');

        inject(function($factory, $httpBackend) {
            mockBackend = $httpBackend;
            fctry = $factory('BaseService', {});
        });
    });

    it('logout() should POST to /logout', function() {
        // I want to test if the logout(cb) function posts to /logout and, on success, redirect to '/'
        // but on failure, calls accessErrors and the cb.
    });
});

This is my karma config file:

files: [
  '../angular.js',
  'node_modules/angular-mocks/angular-mocks.js',

  '../base.js',

  'tests/test_base.js',
],

When I do karma start and run the tests, I get this error / fail:

Chromium 48.0.2564 (Ubuntu 0.0.0) Factory: BaseService logout() should POST to /logout FAILED
    Error: [$injector:unpr] Unknown provider: $factoryProvider <- $factory
    http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24factoryProvider%20%3C-%20%24factory

...

Chromium 48.0.2564 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.053 secChromium 48.0.2564 (Ubuntu 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.114 secs / 0.053 secs)

How come it is failing already and how come it is saying that $factoryProvider is an unknown provider?

Upvotes: 2

Views: 2894

Answers (1)

andyhasit
andyhasit

Reputation: 15289

It thinks you're trying inject factory, which is a function, not a provider, so that won't work.

You're also missing out on the underscore trick

Try changing this:

var fctry, mockBackend;
beforeEach(function() {

    module('BaseApp');

    inject(function($factory, $httpBackend) {
        mockBackend = $httpBackend;
        fctry = $factory('BaseService', {});
    });
});

To this:

var BaseService, $httpBackend;
beforeEach(function() {

    module('BaseApp');

    inject(function(_BaseService_, _$httpBackend_) {
        $httpBackend = _$httpBackend_;
        BaseService = _BaseService_;
    });
});

Upvotes: 2

Related Questions