$httpBackend.whenGET() passThrough() not defined
Asked Answered
B

1

11

I would like to pass some of my http request through and not mock them in my unit test, but when I try to call passThrough() method, an error of missing method is thrown:

"TypeError: Object # has no method 'passThrough'".

Does anybody know how I can fix it please?

There is my code:

'use strict';

describe('Controller: MainCtrl', function () {

    // load the controller's module
    beforeEach(module('w00App'));

    var scope, MainCtrl, $httpBackend;

    // Initialize the controller and a mock scope
    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
        $httpBackend = _$httpBackend_;
        $httpBackend.expectGET('http://api.some.com/testdata.json').passThrough();


        scope = $rootScope.$new();
        MainCtrl = $controller('MainCtrl', {
            $scope: scope
        });
    }));
});
Bartel answered 11/8, 2013 at 14:34 Comment(2)
As explained in the documentation: During unit testing, we want our unit tests to run quickly and have no external dependencies so we don’t want to send XHR or JSONP requests to a real server. The $httpBackend service used in unit tests can't pass through. The $httpBackend used by end-to-end test can, though.Hypanthium
This makes testing directives with external templates more difficult than need be, don't you think?Sirmons
D
3

If you want to mock your backend during development, just install angular-mocks in your main html file, add it up as a dependency in your application (angular.module('myApp', ['ngMockE2E'])) and then mock the requests you need to.

For example;

angular.module('myApp')
  .controller('MainCtrl', function ($scope, $httpBackend, $http) {
    $httpBackend.whenGET('test').respond(200, {message: "Hello world"});
    $http.get('test').then(function(response){
      $scope.message = response.message //Hello world
    })
  });

Be wary though, that adding the ngMockE2E will require you to set up your routes in case you do so through AngularJS routing.

Example;

angular.module('myApp', ['ngMockE2E'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function($httpBackend){
    $httpBackend.whenGET('views/main.html').passThrough();
  })
Drusie answered 4/10, 2013 at 5:24 Comment(2)
You should not add angular-mocks as a dependency to your app, but utilize it in your karma.conf. Then on the beforeEach(module(...)) pass in 'ngMockE2E'.Sucker
+1 gonzofish. Just add beforeEach(function(){module('ngMockE2E');}); in your test. No need to pollute your app with tests stuffs.Lashanda

© 2022 - 2024 — McMap. All rights reserved.