AngularJS Causes mocking httpGET request

so i am new to angularjs and its mocking library. I'm trying to verify that a particular GET request has been made, but I always get this error for the second statement and can't figure out why:

Error: Unsatisfied requests: GET /1.json

      

Is there something I messed up with my code below?

App.js

var App = angular.module('App', []).config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  }).when('/Items', {
    templateUrl: 'views/items.html',
    controller: 'Ctrl'
  }).otherwise({
    redirectTo: '/'
  });
}]);

      

Ctrl.js

function Ctrl($scope, $http, $filter) {
  $scope.items = [];

  $http.get('/1.json').success(function(data) {$scope.items = data.items;});
}

Ctrl.$inject = ["$scope","$http", "$filter"];

      

Spec / Ctrl.js

describe('Controller: Ctrl', function() {
  var $httpBackend;
  // load the controller module
  beforeEach(module('App'));
  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');

    // backend definition common for all tests
    $httpBackend.whenGET('/1.json').respond('Response!');
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  var Ctrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function($rootScope, $controller) {

    scope = $rootScope.$new();
    Ctrl = $controller('Ctrl', {
      $scope: scope
    });
  }));

  it('should initialize with 0 items', function() {
    expect(scope.items.length).toBe(0);
    $httpBackend.flush();
  });

  it('should make store request', function(){
    var controller = scope.$new(Ctrl);
    $httpBackend.expectGET('/1.json');
    $httpBackend.flush();
  });
});

      

EDIT : Added app and controller code.

+3


source to share


1 answer


Finally my unit tests are working! Mainly because I modified my application to make more sense and be more modular.

I will try to provide information to help the next person who comes across this:

at first I switched to using $ resource instead of $ http.

instead of injecting $ injector, I injected $ httpBackend like so:

beforeEach(inject(function(_$httpBackend_, $rootScope, $route,  $controller){

  $httpBackend = _$httpBackend_;
  $httpBackend.expectGET('/path/to/api').respond([{id:1}]);

      

instead of linking "Ctrl" as a string, I passed in the actual class



Ctrl = $controller('Ctrl', { $scope: scope });

became

var ProductsCtrl = ['$scope', function($scope){ ... }];

Ctrl = $controller(ProductsCtrl, {
  $scope: scope
});`

      

Make sure you reference angular-resources.js file if using $ resources

I really love Angularjs; I think it will take a while to wrap my head around how to check. Good luck there!

+4


source







All Articles