Angular 单元测试:如何覆盖 activity 内部服务存根方法订阅

Angular Unit Test: How to cover activity inside service stub method subscriptions

我正在为我的 Angular 组件方法之一编写单元测试,该方法分配 属性 来自服务调用的响应值并调用另一个方法。

我的服务存有响应数据,我在测试中使用订阅中的 expect 语句订阅了它,但它始终将 属性 的值显示为空数组。我已经确认下面测试中的 "response" 包含模拟数据,但无法让组件 属性 "resultSet" 显示为已分配的值。 "toggleSearchForm()" 方法的间谍似乎也从未被调用。

正在测试的方法: search.component.ts

submitSearchCriteria() {
    this.searchService.searchRequest(this.myForm.value)
        .pipe(take(1))
        .subscribe(response => {
            this.resultSet = response;
            this.toggleSearchForm();
        });
}

失败的测试: search.component.spec.ts

it('should assign resultSet to response data and trigger toggle', fakeAsync(() => {
    const spy = spyOn(component, 'toggleSearchForm');
    component.myForm.controls['field1'].setValue('some search query');
    component.myForm.controls['field2'].setValue('something that narrows it down more');

    searchServiceStub.searchRequest(component.myForm.value)
        .subscribe(response => {
            expect(component.resultSet).toContain(response);
            expect(spy).toHaveBeenCalled();
            expect(spy.calls.count()).toBe(1);
        });

    tick();
}))

服务存根: 搜索-service.stub.ts

...
const searchResults = require('./test-data/search-results.json');

searchRequest(searchCriteria) {
    if (!searchCriteria) {
        return of([])
    }
    return of(searchResults);
}

我希望 resultSet 包含存根响应和已调用的间谍,但测试失败并显示以下错误消息:

Expected [  ] to contain [ Object({ thingName: 'thing i was searching for', thingId: 1234 }) ].

Error: Expected spy toggleSearchForm to have been called.

我觉得你的组件测试如果像这样测试组件方法会更有意义。

it('should assign resultSet to response data and trigger toggle', () => {
  const spy = spyOn(component, 'toggleSearchForm');
  const searchService = TestBed.get(SearchService) as SearchService;
  const serviceSpy = spyOn(searchService, 'searchRequest').and.callThrough();
  component.myForm.controls['field1'].setValue('some search query');
  component.myForm.controls['field2'].setValue('something that narrows it down more');

  component.submitSearchCriteria();

  expect(component.resultSet).toEqual([{ thingName: 'thing i was searching for', thingId: 1234 }]);
  expect(serviceSpy).toHaveBeenCalledWith(component.myForm.value);
  expect(spy.calls.count()).toBe(1);
  });

要完成这项工作,您的配置应该类似于

TestBed.configureTestingModule({
  declarations: [SearchComponent],
  providers: [{provide: SearchService, useClass: SearchServiceStub}],
  imports: [ReactiveFormsModule],
})

需要注意的重要变化:

  • 要检查调用的服务是什么,您可以在测试静态结果是否与您的输入匹配之前检查新的 serviceSpy
  • 我们将比较来自您的 search-results.json 的搜索结果,因为这是您的搜索服务返回的内容
  • 不再像您的 component.submitSearchCriteria 中那样订阅,我们现在调用它而不是您的存根服务