我的$ resource-wrapping服务有一个非常简单的单元测试。我有httpBackend模拟和设置返回七个项目的数组。当我运行测试时,它报告已返回4个项目,而不是7:
功能(a1,a2,a3,a4){...}
预计4为7。
以下是我的服务和规格
=== service ===
/* 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;
})
})
=== spec ===
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);
});
});
答案 0 :(得分:3)
试试这个:
<强>服务强>
.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;
});
<强>测试强>
it('gets a list of ledgers', function() {
httpBackend.expect('/rest/api/').respond(ledgerArray);
var result = ledgers.allLedgers();
httpBackend.flush();
expect(result.length).toBe(7);
});