我在AngularJS中创建了以下用于检索对象数组的基本工厂:
angular.
module('core.beer-retriever').
factory('Beer', ['$resource',
($resource) => {
return $resource('https://www.xxxxxxxxx.com/v2/beers', {}, {
query: {
method: 'GET',
isArray: true
},
});
},
]);
我用Jasmine创建了以下测试:
describe('Beer Service', function() {
beforeEach(angular.mock.module('core.beer-retriever'));
beforeEach(inject(function($httpBackend) {
let beersRetrieved = {
results: [{
"id": 192,
"name": "Punk IPA 2007 - 2010",
}]
};
$httpBackend.whenGET('https://api.xxxxxxxxx.com/v2/beers')
.respond(beersRetrieved);
}));
it('is defined', inject(function(Beer) {
expect(Beer).toBeDefined();
}));
it('returns a resource function', inject(function(Beer) {
const output = Beer;
expect(output).toEqual(jasmine.any(Function));
expect(output.query({}.$promise)).toBeDefined();
}));
it('returns beers',
inject(function(Beer) {
const output = Beer.query();
expect(output.length).toEqual(1);
expect(output[0].id).toEqual(192);
httpBackend.flush();
}));
});
前两个测试成功,但第三个测试失败:
Expected 0 to equal 1.
TypeError: Cannot read property 'id' of undefined
at Object.<anonymous> (app/core/beer-retriever/beer-retriever.spec.js:29:25)
at Object.invoke (app/bower_components/angular/angular.js:4862:19)
at Object.WorkFn (app/bower_components/angular-mocks/angular-mocks.js:3170:20)
我无法找出问题所在。有没有人有类似的问题?提前谢谢!
答案 0 :(得分:1)
需要向资源承诺对象添加解析函数。 结帐此工作plunker
output.$promise.then(function(data) {
console.log(data);
output = data[0].results;
});
完整规格看起来如下所示:
it('returns beers',
inject(function(Beer, $httpBackend) {
var output = Beer.query();
output.$promise.then(function(data) {
console.log(data);
output = data[0].results;
});
$httpBackend.flush();
console.log('a11: ' + JSON.stringify(output));
expect(output.length).toEqual(1);
console.log(output[0].id);
expect(output[0].id).toEqual(192);
}));