无法单元测试$ http方法

时间:2017-11-21 13:57:07

标签: javascript angularjs unit-testing karma-jasmine

我有一个像这样的简单控制器方法

$scope.testMethod= function (urlPost) {
    var obj= {
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST',
            data: $scope.prjObj,
            url: urlPost
        };
      if (obj!= undefined) {
           $http(obj).then(function (response) {
           console.log(respone)
          }) 
      //rest of the code
      }}

我正在尝试测试此方法

 beforeEach(angular.mock.inject(function ($injector) {
            $httpBackend = $injector.get('$httpBackend');
            var x ={
                key:'value'
            }
            $httpBackend.when("POST",'/path/to/url',x).respond(200, ["Toyota"]);
 // Rest of the code
})

it("Should check for the testMethod",function(){

        var x ={key:"value"
        }
        $httpBackend.expect('POST','/path/to/url',x).respond({ hello: 'World' });
        createController();
        scope.testMethod("pathToUrl");

        $httpBackend .flush()

    })

我是关注者thisthisthisthis&众多的在线资源,但它仍在投掷

Error: Unexpected request: [object Object] undefined
    Expected POST /path/to/url
        at $httpBackend (node_modules/angular-mocks/angular-mocks.js:1323:9)
        at ChildScope.$scope.addEditProject (testCtrl.js:9:11770)
        at UserContext.<anonymous> (testCtrl-spec.js:201:15)

知道我在哪里弄错了吗?

1 个答案:

答案 0 :(得分:0)

问题在于$http&amp; $httpBackend。控制器期待$http,但它正在注入$httpBackend

创建了一个新变量&amp;像这样注入

$http=$injector.get("$http");