当我使用$ httpBackend后端模拟运行jasmine单元测试时,我遇到了问题。我想测试服务调用返回的值。它调用服务并命中终点,但我不断从方法本身得到错误。不知道我为什么缺少这个功能。任何帮助都非常感谢。
//错误
TypeError: 'undefined' is not an object (evaluating 'data[0].data')
///单元测试
describe("DataService", function () {
describe('testing service', function() {
var TheService, scope;
beforeEach(function () {
module(moduleName);
module('services');
});
beforeEach(inject(function($injector,$rootScope) {
TheService = $injector.get('TheService');
scope=$rootScope.$new();
}));
it('should have a method defined', function() {
expect(TheService.getStuff).toBeDefined();
});
it('should have a method defined', inject(function($httpBackend) {
var mock = { data: 'World' };
$httpBackend.whenGET("/theurl/getStuff").respond({ data: 'World' });
$httpBackend.expectGET("/theurl/getStuff");
TheService.getStuff();
scope.$digest();
expect(TheService.getStuff).toEqual(mock);
$httpBackend.flush();
}));
});
});
//服务方法
function TheService($http, $q) {
var vm = this;
vm.getStuffs = null;
vm.getStuff = getStuff;
vm.theresponse = {};
function getStuff() {
var deferred = $q.defer();
$http({
method: 'GET',
url: "/theurl/getStuff"
}).success(function(data){
vm.theresponse = data[0].data
deferred.resolve(vm.theresponse);
}).error(function(){
deferred.reject('An error occurred');
});
return deferred.promise;
}
}
答案 0 :(得分:2)
嗯,假端点返回
{ data: 'World' }
但该服务试图访问
data[0].data
数据是一个对象。它不是一个数组。所以data[0]
未定义。
要使服务代码正常工作,您应该返回类似
的内容[{ data: 'World' }]
此外,您的代码使用promise antipattern,并且不推荐使用成功和错误回调。阅读http://blog.ninja-squad.com/2015/05/28/angularjs-promises/以获得更好的选择: