Inside a function (ngOnInit
in this case) I'm subscribing to an observable. When I get new data, I update another function with that data:
ngOnInit(): void {
this.observable$.subscribe({
next: (data) => {
this.function(data)
},
});
}
function(data): void {
console.log(data)
}
The problem comes when I need to test this. I've tried the approaches of all online answers I could find, such as In Jest, how can I unit test a method that subscribes to an observable (I don't have a service I'm mocking) and Angular - Function inside subscribe never called in unit test (not Jest), and below is my current attempt:
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();
},
});
});
});
But I get numberOfCalls: 0 from this one.