2017-08-24 72 views
0

我有一个角服务,我想测试一个承诺,一个get函数返回转换的数据:测试嘲笑可观察转换成角

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) 
     }); 
    } 
} 

我如下测试此:

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) 
      }); 
    })); 
}); 

这将返回一个错误:

response.json is not a function 

东西[]具有12的长度,但有在最后一个切片然后(),它应只返回10. 我是茉莉花相当新,所以可能很容易错过这里的一些基本面。任何帮助表示赞赏

+1

“响应”未定义? – Joe

+0

实际上,响应是一个json数组,它可能是问题,不适合将其转换为字符串并测试 –

+0

嗯,如果它已经是JSON,那么你需要调用'.json()'吗? – Joe

回答

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

这确实有效,但它是测试服务的“正确”方式吗?我猜想.json()方法不属于测试的主题,在这种情况下我的服务,我仍然试图找出在这个世界上被认为是脏的东西 –

+0

是的,这实际上是正确的方式,你正在嘲笑这个回应。有更好的方法,但他们都属于这种方式 – Milad

+1

不要太担心脏兮兮,最后总是很脏 – Milad