我的 $resource-wrapping 服务有一个非常简单的单元测试。我已经模拟并设置了 httpBackend 以返回包含七个项目的数组。当我运行测试时,它报告返回了 4 个项目,而不是 7 个:
函数 (a1, a2, a3, a4) { ... }
预计 4 为 7。
以下是我的服务和规格
=== 服务 ===
/* original
angular.module('TeamSportApp')
.factory('LedgerService', function ($resource) {
var Ledgers = $resource("/rest/api", { id: '@id'},
{
allLedgers : { method: 'GET', isArray: true},
postTransaction : { method: 'POST'},
removeTransaction : { method: 'DELETE'}
});
return Ledgers;
})*/
/* Fixed */
.factory('LedgerService', function ($resource) {
var Ledgers = $resource("/rest/api/:id", { id: '@id' },
{
allLedgers : { method: 'GET', isArray: true},
postTransaction : { method: 'POST'},
removeTransaction : { method: 'DELETE'}
});
return Ledgers;
})
})
=== 规格 ===
var ledgerArray = [
{id:1, name:"Master Ledger"},
{id:2, name:"User1 Ledger"},
{id:3, name:"User2 Ledger"},
{id:4, name:"User3 Ledger"},
{id:5, name:"User4 Ledger"},
{id:6, name:"User5 Ledger"},
{id:7, name:"User6 Ledger"}
];
ddescribe('Ledger service test', function(){
var ledgers, httpBackend;
beforeEach(module('TeamSportApp','ngResource'));
beforeEach(inject(function ($injector) {
ledgers = $injector.get("LedgerService");
httpBackend = $injector.get("$httpBackend");
}));
afterEach (function () {
httpBackend.verifyNoOutstandingExpectation ();
httpBackend.verifyNoOutstandingRequest ();
});
/* ORIGINAL ERROR
it('gets a list of ledgers', function() {
httpBackend.when('/rest/api').respond(ledgerArray);
var result = ledgers.allLedgers;
console.log(result);
expect(result.length).toBe(4);
//httpBackend.flush();
});*/
/* All fixed using angular1.2.14 per [this][1] */
it('gets a list of ledgers', function() {
httpBackend.expectGET('/rest/api').respond(ledgerArray);
var result = ledgers.allLedgers();
httpBackend.flush();
expect(result.length).toBe(7);
});
it('gets a single ledger', function() {
httpBackend.expectGET('/rest/api/2').respond(singleLedger);
var result = ledgers.get({id:2});
httpBackend.flush();
console.log(result);
expect(result.name).toBe(singleLedger.name);
});
});