After completing the Angular tour of heroes, I delved into writing tests for it. While some tests were straightforward to write, I encountered difficulties when attempting to fetch data from the server. Despite researching topics like testing controllers, defers, marbles, and schedulers, I find myself at a standstill with no clear direction on how to proceed. The outcome either results in persistent test failures or passing tests with 'SPEC HAS NO EXPECTATIONS', which essentially equates to an empty test.
//Test
it('#updateHero() works', waitForAsync(inject([HeroService], (service: HeroService) => {
let testHero = {
id: 42,
name: 'TestHero'
} as Hero
service.updateHero(testHero).subscribe()
service.getHero(42).subscribe(hero => expect(hero.name).toBe('TestHero'))
})));
//service
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`
return this.http.get<Hero>(url).pipe(
tap(_ => this.messageService.add(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`)))}
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe(
tap(_ => this.messageService.add(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
)}
In several other tests, I faced the same challenge where my services failed to retrieve any data despite the application itself functioning flawlessly.
My colleagues provided little help in addressing my concerns, offering unconventional suggestions like mocking the entire server response instead.