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
});
}));