我知道还有一个类似的问题here
但是我正在执行建议的答案,但仍然出现此错误
基本上我有这样的功能
checkForInvitation() {
this._join.joinInformationSource.pipe(filter(x => x !== null)).subscribe(result => {
this.joinInformation = result;
this.setFields(result.userInfo);
});
}
基本上,它获取信息,然后调用另一种方法来预填充某些表单字段。
现在我正在尝试测试此方法,因此我创建了一个像这样的间谍...
// ...
const joinServiceSpy = jasmine.createSpyObj('JoinService', ['joinInformationSource']);
// ...
providers: [
{ provide: JoinService, useValue: joinServiceSpy }
]
// ...
joinService = TestBed.get(JoinService);
it('should prepopulate fields if there is join information', () => {
let joinInfoSpy = joinService.joinInformationSource.and.returnValue(
of(
// ... object
)
)
});
现在当我执行ng test时,我会反复收到此错误
this._join.joinInformationSource.pipe is not a function
这是我的joinService
joinInformationSource = new BehaviorSubject<JoinInformation>(null);
setJoinInformation(joinInformation: JoinInformation) {
this.joinInformationSource.next(joinInformation);
}
我在这里做什么错了?
答案 0 :(得分:1)
根据文档createSpyObj,将方法列表作为第二个参数。因此,在创建模拟对象时,您将joinInformationSource
创建为函数。
const joinServiceSpy = jasmine.createSpyObj('JoinService', ['joinInformationSource']);
//now joinSeverSpy contains method joinInformationSource
但是在您的代码中,您使用joinInformationSource
作为字段
// _join.joinInformationSource has been used as a field
this._join.joinInformationSource.pipe(filter(x => x !== null)).subscribe(result => {
this.joinInformation = result;
this.setFields(result.userInfo);
});
由于joinInformationSource
是一个函数,因此它肯定没有pipe
方法。解决方案很少。其中之一是使用spyOnProperty方法:
//create a service object and define a property
const joinService: any = new Object();
Object.defineProperty(joinService, 'joinInformationSource', {get: () => {}});
//then create a spy on the property
it('should prepopulate fields if there is join information', () => {
let joinInfoSpy = spyOnProperty(joinService, 'joinInformationSource', 'get')
.and.returnValue(
new BehaviorSubject<JoinInformation>(//object)
)
}
//the rest of the code
);