【发布时间】:2021-11-10 22:00:44
【问题描述】:
在函数内部(在这种情况下为ngOnInit),我订阅了一个可观察对象。当我获得新数据时,我会使用该数据更新另一个函数:
ngOnInit(): void {
this.observable$.subscribe({
next: (data) => {
this.function(data)
},
});
}
function(data): void {
console.log(data)
}
当我需要对此进行测试时,问题就来了。我已经尝试了我能找到的所有在线答案的方法,例如In Jest, how can I unit test a method that subscribes to an observable(我没有我在嘲笑的服务)和Angular - Function inside subscribe never called in unit test(不是开玩笑),以下是我目前的尝试:
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Modules],
providers: [provideMock({})],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component['observable$'] = { subscribe: jest.fn() } as unknown as Observable<Type>;
fixture.detectChanges();
});
describe('ngOnInit', () => {
it('should call function with Data', (done) => {
const holdingsAndCashAccounts = [mockHolding(), mockCashAccount()];
jest.spyOn(component, 'function')
component['observable$'] = of(observableContent);
component['observable$'].subscribe({
next: (data) => {
expect(component.function).toHaveBeenCalledWith(data);
done();
},
});
});
});
但我从这个得到 numberOfCalls: 0。
【问题讨论】:
-
你为什么要订阅测试中的 observable,或者监视你应该测试的东西?为什么 test double 不是一个真正的 observable,而不仅仅是一个具有 subscribe 属性的对象?测试行为:给定一个发出值的可观察对象,该值是否被记录?
-
@jonrsharpe 感谢您的回复。我已经在这几个小时了,这只是我最近的尝试——但我想要测试的是,函数是用数据调用的。我不太确定你在建议我做什么,你有没有机会为我改写一下或举个例子?