角度单元测试:如何涵盖服务存根方法订阅中的活动

时间:2019-09-11 16:05:58

标签: angular jasmine subscribe rxjs-observables

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

我在服务中添加了响应数据,并在测试中使用预订内的Expect语句预订了该服务,但该服务始终将属性值显示为空数组。我已经确认以下测试中的“响应”包含模拟数据,但无法获取组件属性“ 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();
}))

服务存根: search-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.

1 个答案:

答案 0 :(得分:1)

我认为,如果您像这样测试组件方法,则组件测试将更有意义。

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(而不是您的存根服务)中呼叫