2017-08-24 52 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