J'ai un service angulaire Je veux tester, une fonction retourne obtenir les données transformées:Test d'un converti Observable moqué d'une promesse angulaire
getSomeThings(pageSize) {
return this.http
.get(`../assets/things.json`)
.map((response) => response.json())
.toPromise()
.then(response => {
return response.map((thing) => {
return new Thing(thing);
});
}).then(response => {
response.slice(0, pageSize)
});
}
}
Je teste cela comme ci-dessous:
describe('ThingsService',() => {
let service: ThingsService;
let mockHttp;
const things = [{ id: 1, title: 'hello' }, { id: 2, title: 'hello' }, { id: 3, title: 'hello' }, { id: 4, title: 'hello' },
{ id: 5, title: 'hello' }, { id: 6, title: 'hello' }, { id: 7, title: 'hello' }, { id: 8, title: 'hello' }, { id: 9, title: 'hello' },
{ id: 10, title: 'hello' }, { id: 11, title: 'hello' }, { id: 12, title: 'hello' }];
beforeEach(() => {
mockHttp = new Http(undefined, undefined)
service = new ThingsService(mockHttp);
spyOn(mockHttp, 'get').and.returnValue(Observable.of(things)).and.callThrough();
});
it('should have a length of 10', async(() => {
mockHttp.get.and.returnValue(Observable.of(things));
return service.getThings(10)
.then((returnedThings: any[]) => {
expect(returnedThings.length).toBe(10)
});
}));
});
Cette renvoie une erreur:
response.json is not a function
choses [] a une longueur de 12, mais il y a une tranche en finale alors() qui devrait Je reviens tout juste à Jasmine, donc je pourrais facilement manquer certains principes fondamentaux ici. Toute aide appréciée
Est-ce que 'response' est indéfini? – Joe
En fait, la réponse est un tableau json, ce qui peut être le problème, ill convertir en une chaîne et tester –
Hmm, si c'est déjà JSON, alors vous aurez besoin d'appeler '.json()' sur elle? – Joe