繁体   English   中英

如何测试使用 http.get 的 Angular 函数?

[英]How to test Angular functions that use http.get?

我完成了Angular英雄之旅,开始为它写测试。 有些很容易编写,但是当我尝试从服务器获取数据时,它就不起作用了。 我已经阅读了有关测试 controller、defer、弹珠、调度程序之类的东西,但我仍然不知道如何进行。 我要么永久测试失败,要么测试通过“SPEC HAS NO EXPECTATIONS”,这也没有带来任何结果,因为它本质上只是一个空测试。

//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'))
)}

在其他一些测试中,我遇到了同样的问题,他们只是没有从我的服务中得到任何东西,但是实际的应用程序运行良好。

我的同事并没有真正回答我的问题,除了一些奇怪的决定,比如 mocking 整个服务器响应。

经过很长时间尝试我能找到的任何东西,我想出了以下解决方案:

...
beforeEach(async () => {
let router = {
  snapshot: {
    paramMap: {
      get: () => 1, // represents the bookId
    },
  },
};

await TestBed.configureTestingModule({
  declarations: [ DetailComponent ],
  imports: [ HttpClientTestingModule ],
  providers: [
    {
      provide: ActivatedRoute,
      useValue: router
    },
  ],
})
.compileComponents();

...
});

it('http.get hero works', () => {
const heroes: Hero[] = [
  { id: 1, name: 'Fake Batman1', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
  { id: 2, name: 'Fake Batman2', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
  { id: 3, name: 'Cool Batman', imgSrc: '../assets/Batman.jpg', score: 20, commentary: 'The coolest batman ever' },
  { id: 4, name: 'Fake Batman3', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
  { id: 5, name: 'Batman', imgSrc: '../assets/Batman.jpg', score: 3, commentary: 'No opinion' },
  { id: 6, name: 'Fake Batman4', imgSrc: '../assets/Batman.jpg', score: -5, commentary: 'FAKE!!!!!' },
]
const req = httpTestingController.expectOne('api/heroes/1');
expect(req.request.method).toEqual('GET');
req.flush(heroes[2]);
httpTestingController.verify();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM