我需要在代码中用 Jasmine 覆盖这个方法
private subject = new Subject<any>();
getMessage(): Observable<any> {
return this.subject.asObservable();
}
这是我的构造函数
fiscalDocument: FiscalDocumentData;
subscription: Subscription;
constructor(private _myFiscalDocumentsService: MyFiscalDocumentsService) {
this.subscription = this._myFiscalDocumentsService.getMessage().subscribe(message => {
if (message) {
this.fiscalDocument = message;
} else {
this.fiscalDocument = null;
}
});
}
我已经在测试中尝试过这样做,我有 TestBed.confiugreTestingModule,但我不会在这里发帖,因为我相信那是我的问题不存在
let dummyOb: Observable<any>;
beforeEach(() => {
service = TestBed.get(MyFiscalDocumentsService);
fixture = TestBed.createComponent(MyFiscalDocumentsDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should getMessage', async () => {
let generalSpy = spyOn(service, 'getMessage' ).and.returnValue(await Promise.resolve(dummyOb));
expect(generalSpy).toHaveBeenCalled();
});
错误消息:预期 spy getMessage 已被调用。 编辑:我得到了 if 条件,现在我正在尝试 else
最佳答案
在构造函数中使用一些复杂的逻辑是不好的做法,请使用 ngOnInit 代替:Difference between Constructor and ngOnInit
关于angular - 测试在构造函数上使用 observable 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58063201/