vendredi 22 janvier 2016

Angular Unit Test: Cannot read property 'get' of undefined

I am trying to test the http get below,

app.controller('GetReposController', ['$scope', '$http', function($scope, $http) {

    $http.get('http://ift.tt/1NsLpbA')
      .success(function(data, status, headers, config) {
        $scope.valid = true;
        $scope.response = data;
      })
      .error(function(data, status, headers, config) {
        $scope.valid = false;
    });

my test spec,

describe('GetReposController Test', function() {

    // Boilerplate starts from here...
    // Load the module with MainController
    beforeEach(module('myApp'));

    var controller, $scope, $http, $httpBackend;

    // inject the $controller and $rootScope services.
    // in the beforeEach block.
    beforeEach(inject(function ($rootScope, $controller) {

        // Create a new scope that's a child of the $rootScope.
        $scope = $rootScope.$new();

        // Create the controller.
        controller = $controller;
        controller("GetReposController", {$scope, $http, $httpBackend});
    }));
    // ...Boilerplate ends here

    // Our tests will go here.
    it('should demonstrate using when (200 status)', inject(function($http, $httpBackend) {

      var $scope = {};

      /* Code Under Test */
      $http.get('http://ift.tt/1NsLpbA')
        .success(function(data, status, headers, config) {
          $scope.valid = true;
          $scope.response = data;
        })
        .error(function(data, status, headers, config) {
          $scope.valid = false;
      });
      /* End */

      $httpBackend
        .when('GET', 'http://ift.tt/1TcNmtF')
        .respond(200, { foo: 'bar' });

      $httpBackend.flush();

      expect($scope.valid).toBe(true);
      expect($scope.response).toEqual({ foo: 'bar' });

    }));
 });

I get two errors,

TypeError: Cannot read property 'get' of undefined

and

Error: Unexpected request: GET http://ift.tt/1NsLpbA No more request expected

Any ideas what have I done wrong??

Aucun commentaire:

Enregistrer un commentaire