我有一個角服務,我想測試一個承諾,一個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. 我是茉莉花相當新,所以可能很容易錯過這裏的一些基本面。任何幫助表示讚賞
「響應」未定義? – Joe
實際上,響應是一個json數組,它可能是問題,不適合將其轉換爲字符串並測試 –
嗯,如果它已經是JSON,那麼你需要調用'.json()'嗎? – Joe