mi sto cercando di fare una prova di unità di un servizio nel mio casoCome scrivere un test unitario per la richiesta http?
Nel mio test controller
myService.getItem('/api/toy/' + scope.id).success(
function(toy) {
$scope.toy = toys.details;
}
);
MyService
angular.module('toyApp').service('myService', ['$http',
function($http) {
var service = {};
return {
getItem: function(url) {
return $http.get(url);
},
};
}
]);
file di prova.
describe('toy ctrl', function() {
var $httpBackend, ctrl, myService;
beforeEach(module('toyApp'));
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, __myService_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
myService = _myService_;
ctrl = _$controller_('toyCtrl', {
$scope: scope
});
}));
describe('call my service', function() {
it('should make request when app loads', function() {
$httpBackend.expectGET('/api/toy/123').respond({id:123, detail:456 });
myService.getItem('/api/toy/123').then(function(toy){
expect(scope.toy.detail).toBe(456);
})
$httpBackend.flush();
})
})
sto ottenendo
Error: Unexpected request: GET /api/toy/123
No more request expected
Se prendo $httpBackend.flush()
, l'errore è andato ma non coprirà la parte
function(toy) {
$scope.toy = toys.details;
}
. Voglio coprire la chiamata di funzione e non sono sicuro di come farlo. Qualcuno può aiutarmi? Grazie mille
Sei unità di test del controller o servizio (dovrebbe fare richiesta quando i carichi dell'app sembra li controller ke)? – PSL
Sto testando il servizio all'interno del mio controller – FlyingCat
Ok. in quel caso potresti semplicemente prendere in giro il tuo servizio e iniettarlo sul controller. E il valore del test rispetto all'ambito. Fondamentalmente quello che sto cercando di dire è che quando si controlla l'unità di test del controller è sufficiente testare la logica del controller 'myService.getItem ('/ api/toy/123')' è irrilevante in realtà. – PSL