Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS-http获取JSON文件的单元测试_Angularjs_Unit Testing_Angularjs Scope_Jasmine_Karma Jasmine - Fatal编程技术网

AngularJS-http获取JSON文件的单元测试

AngularJS-http获取JSON文件的单元测试,angularjs,unit-testing,angularjs-scope,jasmine,karma-jasmine,Angularjs,Unit Testing,Angularjs Scope,Jasmine,Karma Jasmine,我试图编写一个单元测试来测试一个简单的工厂,它执行http.get来检索JSON文件 工厂在我的控制器内调用 这是一个plunker,显示了我的http.get: Ctrl: 工厂: app.factory('factoryGetJSONFile', function($http) { return { getMyData: function(done) { $http.get('data.json') .success(function(data) {

我试图编写一个单元测试来测试一个简单的
工厂
,它执行
http.get
来检索JSON文件

工厂在我的控制器内调用

这是一个plunker,显示了我的http.get:

Ctrl:

工厂:

app.factory('factoryGetJSONFile', function($http) {
  return {
    getMyData: function(done) {
      $http.get('data.json')
      .success(function(data) {
        done(data);
      })
      .error(function(error) {
        alert('An error occured whilst trying to retrieve your data');
      });
    }
  }
});
测试:

错误:

TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')

您应该在每个之前将
$httpBackend
分配给
中的
httpock
,如下所示:

   beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
        httpMock = $httpBackend;
        scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {
            $scope: scope,
            factoryGetJSONFile: factoryGetJSONFile,
            $httpBackend: httpMock
        });
    }));

您在哪里定义服务对象?正如您的代码现在所示,只有编写factoryGetJSONFile:factoryGetJSONFile时,它才会编译,但它只会调用原始服务。您必须定义一个模拟服务并将其放在服务中为什么在beforeach和ctrl参数中定义它?尝试了您的代码,得到一个错误:错误:意外请求:get/data.json?预期的GET/data.json在哪里?来自??
TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')
   beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
        httpMock = $httpBackend;
        scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {
            $scope: scope,
            factoryGetJSONFile: factoryGetJSONFile,
            $httpBackend: httpMock
        });
    }));