AngularJS - http 到 JSON 文件的单元测试 [英] AngularJS - Unit test for http get to JSON file
本文介绍了AngularJS - http 到 JSON 文件的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个单元测试来测试一个简单的 factory
,它执行一个 http.get
来检索 JSON 文件.
I am trying to write a unit test to test a simple factory
that performs a http.get
to retrieve a JSON file.
工厂在我的控制器中被调用.
The factory is called within my controller.
这是一个显示我的 http.get 的 plunker:http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=预览
Here's a plunker showing my http.get: http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=preview
控制:
app.controller('MainCtrl', function($scope, $http, factoryGetJSONFile) {
factoryGetJSONFile.getMyData(function(data) {
$scope.Addresses = data.Addresses.AddressList;
$scope.People = data.Names.People;
});
});
工厂:
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');
});
}
}
});
测试:
// ---SPECS-------------------------
describe('with httpBackend', function () {
var app;
beforeEach(function () {
app = angular.mock.module('plunker')
});
describe('MyCtrl', function () {
var scope, ctrl, theService, httpMock;
beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
scope = $rootScope.$new(),
ctrl = $controller('MyCtrl', {
$scope: scope,
factoryGetJSONFile: theService,
$httpBackend: httpMock
});
}));
it("should make a GET call to data.json", function () {
console.log("********** SERVICE ***********");
httpMock.expectGET("data.json").respond("Response found!");
//expect(factoryGetJSONFile.getMyData()).toBeDefined();
httpMock.flush();
});
})
});
错误:
TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')
推荐答案
你应该将 $httpBackend
分配给 beforeEach
中的 httpMock
像这样:
You should assign $httpBackend
to httpMock
in beforeEach
like this:
beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
httpMock = $httpBackend;
scope = $rootScope.$new();
ctrl = $controller('MyCtrl', {
$scope: scope,
factoryGetJSONFile: factoryGetJSONFile,
$httpBackend: httpMock
});
}));
这篇关于AngularJS - http 到 JSON 文件的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文