使用$ httpBackend测试角度控制器时出现奇怪的错误

时间:2014-04-03 13:02:13

标签: javascript angularjs unit-testing jasmine karma-runner

我一直试图修复它几个小时。不幸的是有负面影响所以请帮助我。

在我的应用程序中,我想测试我的$ http请求。我是通过使用$ httpBackend来实现的。

这是我的控制器代码:

angular.module('app').controller('testController',function($scope,$http){
 $http.get('/test/users').success(function(data){
        console.log('wtf');
    });
})

我的单元测试代码:

describe('testController tests', function(){
    var $httpBackend, $scope, createController;
    beforeEach(module('app'));
    beforeEach(inject(function($injector, ngTableParams, notifier,identity, $sessionStorage, $location){

        $httpBackend = $injector.get('$httpBackend');

        $httpBackend.whenGET('/test/users').respond({test: 'test'});

        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();
        var $controller = $injector.get('$controller');


        createController = function(){
          return $controller('testControler', { '$scope': $scope, '$http': $httpBackend });
        };


    }));

    it('should fetch users ', function() {
        $httpBackend.expectGET('/test/users');
        var controller = createController();
        $httpBackend.flush();
    });

});

它无法正常工作。我总是有以下错误:

TypeError: Object function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {
var xhr = new MockXhr(),
    expectation = expectations[0],
    wasExpected = false;

function prettyPrint(data) {
  return (angula...<omitted>... } has no method 'get'
at new <anonymous> (http://localhost:9876/base/public/app/controllers/testController.js:256:11)
at invoke (http://localhost:9876/base/public/libraries/angular/angular.js:3805:17)
at Object.instantiate (http://localhost:9876/base/public/libraries/angular/angular.js:3816:23)
at $get (http://localhost:9876/base/public/libraries/angular/angular.js:6922:28)
at createController (http://localhost:9876/base/test/unit/testControllerSpec.js:70:18)
at null.<anonymous> (http://localhost:9876/base/test/unit/testControllerSpec.js:89:26)
at jasmine.Block.execute (http://localhost:9876/base/node_modules/karma-jasmine/lib/jasmine.js:1145:17)
at jasmine.Queue.next_ (http://localhost:9876/base/node_modules/karma-jasmine/lib/jasmine.js:2177:31)
at http://localhost:9876/base/node_modules/karma-jasmine/lib/jasmine.js:2167:18 

任何想法是什么意思以及如何解决它?

2 个答案:

答案 0 :(得分:1)

我的代码中发现了错误。 $ httpBackend不应该注入控制器。

答案 1 :(得分:0)

我认为问题是您需要将依赖项添加到模块创建中:

angular.module('app', []).controller ...

而不是

angular.module('app').controller ...