我对Jasmine和Angular的单元测试很新,所以请耐心等待我:)
我正在尝试为一个方法编写单元测试,该方法应该返回类型为ArtworkDetail
的对象,但不希望服务进行实际的http调用。我听说过嘲笑数据和嘲弄服务,但我不知道如何自己做。我在单元测试文件中制作模拟对象还是创建模拟服务?任何指针都表示赞赏!
app.component.ts
public setArtworkDetail(id: string): void {
this.details = undefined;
this.artworksService.getArtworkDetail(id)
.subscribe((detailData: ArtworkDetail) => {
this.details = detailData;
});
}
app.component.spec.ts
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
IndexComponent,
DetailsComponent,
NavbarComponent
],
providers: [
{provide: ArtworksService, class: MockArtworksService}
]
}).compileComponents();
}));
it('should return an ArtworkDetail when calling setArtworkDetail()', (() => {
...
}));
艺术品-detail.model.ts
export interface ArtworkDetail {
id: string;
title: string;
url: string;
year: number;
description: string;
artist: string;
}
答案 0 :(得分:3)
您说明要使用模拟是正确的。 Angular实际上有一个很好的tutorial page on it
一般要点是,您在before方法中提供此类,然后让它返回相关数据。 IMO是该页面的最佳例子:
it('getHeroes() should return some heroes', fakeAsync(() => {
let result: String[];
this.heroService.getHeroes().then((heroes: String[]) => result = heroes);
this.lastConnection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify({data: [HERO_ONE, HERO_TWO]}),
})));
tick();
expect(result.length).toEqual(2, 'should contain given amount of heroes');
expect(result[0]).toEqual(HERO_ONE, ' HERO_ONE should be the first hero');
expect(result[1]).toEqual(HERO_TWO, ' HERO_TWO should be the second hero');
}));
要验证调用某个方法,您需要创建a spy。创建后,您只需致电
expect(ArtworkServiceSpy.setArtworkDetail.calls.count())
.toBe(1, 'spy method was called once');