2017-08-24 1 views
0

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

+1

Est-ce que 'response' est indéfini? – Joe

+0

En fait, la réponse est un tableau json, ce qui peut être le problème, ill convertir en une chaîne et tester –

+0

Hmm, si c'est déjà JSON, alors vous aurez besoin d'appeler '.json()' sur elle? – Joe

Répondre

0
const things = { 
     json:function(){ 
      return [{ 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' }]; 
     } 

    } 
+0

Cela fonctionne, mais est-ce le moyen «correct» de tester un service? Je suppose que la méthode .json() n'appartient pas au sujet du test, dans ce cas mon service, j'essaie toujours de trouver ce qui est considéré comme sale dans ce monde –

+0

oui, c'est en fait la bonne façon, se moquent de la réponse. Il y a de meilleurs moyens, mais ils tombent tous dans cette voie – Milad

+1

Et ne vous inquiétez pas trop de la saleté, c'est toujours sale à la fin – Milad