Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS testing error: Unknown provider: $_httpBackend_Provider <- $_httpBackend_

I am attempting to test an AngularJS controller with a Jasmine unit test spec file. My approach is to use $httpBacked, in the following test:

describe('SubmissionsController', function() {
    var minimal_mock_response = [ { id: 1 } ]; 
    var scope, routeParams, $httpBackend; 

    beforeEach(module('submissionServices'));

    beforeEach(inject(function($_httpBackend_, $rootScope) {
        scope = $rootScope.$new();  
        $httpBackend = $_httpBackend_;
        $httpBackend.expectGET('/submissions').respond(minimal_mock_response);
        routeParams = {};
    }));

    it('passes a trivial test', function() {
        expect(true).toBe(true);
    });
});

I inserted the expect(true).toBe(true) just to get the test to execute and fail, even though it does not touch the angular controller. When I I attempt to run the test with jasmine-headless-webkit, I receive the following error:

jasmine-headless-webkit spec/javascripts/SubmissionsControllerSpec.js

Running Jasmine specs...
F
FAIL: 1 test, 1 failure, 0.011 secs.

Submissions controllers SubmissionsController passes a trivial test.     (XXX/spec/javascripts/SubmissionsControllerSpec.js:18)
Error: Unknown provider: $_httpBackend_Provider <- $_httpBackend_

Test ordering seed: --seed 9254 

Are there any hints on how I can correct this error and make the trivial test execute?

like image 860
oxirane Avatar asked Oct 23 '12 21:10

oxirane


2 Answers

Enclosing service names with underscores has some benefit.

From your code, I can see that you probably wanted to save the reference to $httpBackend. This is how you wanted to do. The placement of underscore was one off.

beforeEach(inject(function(_$httpBackend_, $rootScope) {
    scope = $rootScope.$new();  
    $httpBackend = _$httpBackend_;
    ...

Angular is smart enough to remove underscores and returns $httpBackend back to you, and you can save it to your own $httpBackend.

like image 144
ghiden Avatar answered Nov 04 '22 02:11

ghiden


I believe this is because you're injecting the wrong service. It doesn't know what $_httpBackend_ is. You should be able to just do this:

beforeEach(inject(function($httpBackend, $rootScope) {
    scope = $rootScope.$new();  
    $httpBackend.expectGET('/submissions').respond(minimal_mock_response);
    routeParams = {};
}));

If you want to get a reference to the $httpBackend service once and store that as $httpBackend, ghiden's answer is the way to go.

like image 1
dnc253 Avatar answered Nov 04 '22 03:11

dnc253