【问题标题】:Angular Jasmine: Unit testing a method that is calling a service without doing actuall http callAngular Jasmine:对调用服务的方法进行单元测试而不进行实际的 http 调用
【发布时间】:2018-09-04 17:37:30
【问题描述】:

我对 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()', (() => {

  ...

  }));

artwork-detail.model.ts

export interface ArtworkDetail {
  id: string;
  title: string;
  url: string;
  year: number;
  description: string;
  artist: string;
}

【问题讨论】:

    标签: angular unit-testing http jasmine mocking


    【解决方案1】:

    您说要使用模拟是正确的。 Angular 其实有一个不错的tutorial page on it

    一般的要点是你在前面的方法中提供这个类,然后让它返回相关数据。 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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2014-08-15
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多