user3821415
user3821415

Reputation: 243

Dependency injection not working in angular/browserify/karma/jasmine unit test

I'm using Browserify in conjunction with Angular and testing with Karma and Jasmine. I'm trying to test a factory function that uses $http. Here's a look at the factory:

module.exports = function($http) {
  var messageFactory = {};
  messageFactory.fetchAll = function(url) {
    $http.get(url).success(function() {
      console.log('success');
    });
  }

  return messageFactory
}

Here's the test:

var angular = require('angular');
var messageFactoryModule = require('./message.factory.js');
require('angular-mocks');


describe('Factory: Message', function() {
  var messageFactory;
  var $httpBackend;
  var url;

  beforeEach(inject(function(_$httpBackend_) {
    $httpBackend = _$httpBackend_;
    messageFactory = new messageFactoryModule();
    url = 'http://example.com';
  }));

  describe('when fetch is called', function() {
    it('should fetch messages from the database', function() {
      $httpBackend.expectGET(url)
        .respond({});

      messageFactory.fetchAll(url);

      $httpBackend.flush();
    });    
  });
});

When I run the test, I get an error because $http is not defined in the factory

TypeError: Cannot read property 'get' of undefined

I similarly get errors when I try to inject other services like $filter and see if it's defined. When I actually run Message.fetchAll in the Angular app, everything works fine. Obviously there's something wrong with my test setup, I just can't figure out what.

Thanks

Upvotes: 4

Views: 4019

Answers (1)

user3821415
user3821415

Reputation: 243

I changed my beforeEach block to this:

  beforeEach(inject(function(_$httpBackend_, $http) {
    $httpBackend = _$httpBackend_;
    messageFactory = new messageFactoryModule($http);
    url = 'http://example.com';
  }));

The change being that I'm now passing $http into the module. Still not 100% sure this is correct, but everything seems to work as expected.

Upvotes: 3

Related Questions