【发布时间】:2019-10-30 22:11:33
【问题描述】:
我有一个依赖于 SearchAttributeService 的组件。有一个名为searchAttributeValidation 服务的方法返回一个Subject。我正在订阅这个主题:
attributeSearchValidation(): void {
this._searchAttributeService.searchAttributeValidation.subscribe((value: string) => {
if (value === this._searchAttributeService.emptyAttributeSearchData) {
this.searchAttributeIndicator = true;
} else if (value === this._searchAttributeService.clearEmptyAttributeSearchDataValidation) {
this.searchAttributeIndicator = false;
});
}
get searchAttributeValidation(): Subject<string> {
return this.searchAttributeValidationSubject;
}
我正在尝试像这样测试这种方法:
searchAttributeService = TestBed.get(SearchAttributeService);
let spy = spyOn(searchAttributeService, 'searchAttributeValidation').and.returnValue(of('EMPTY-DATA'));
component.attributeSearchValidation();
expect(spy).toHaveBeenCalled();
expect(component.searchAttributeIndicator).toBeTruthy();
在测试过程中根本不调用 searchAttributeValidation 方法。我什至提供了服务 TestBed.configureTestingModule({
测试失败并显示以下消息:Expected spy searchAttributeValidation to has been called.
我哪里错了??花了一整天的时间,还是没搞清楚问题?
【问题讨论】:
-
您在日志中收到的错误是什么?
-
@AjayReddy 应调用间谍 searchAttributeValidation。
-
'searchAttributeValidation' 是一个可观察的对象,而不是一个方法。 'spyOn' 可用于方法而不是对象。
-
@AshishPatel searchAttributeValidation 是一个 getter 方法,它返回一个可观察的 get searchAttributeValidation(): Subject
{ return this.searchAttributeValidationSubject; } -
您正在模拟服务,然后期望调用实际的服务方法....相反,您需要检查 subscribe 方法中的值的测试,例如 expect(searchAttributeIndicator).toBeTruthy() ...等
标签: angular jasmine karma-jasmine spy angular-test