I have a component using fromEvent to add a click listener to the whole document:
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyComponent {
onClick = fromEvent(this._windowRef.nativeWindow.document, 'click')
.pipe(
skip(1),
filter((event: MouseEvent) => this._doStuff()),
)
.subscribe(() => {
// do stuff
});
}
But in the test, I got an error when instancing the component:
TypeError: Cannot read property 'pipe' of undefined
At the pipe after the fromEvent
This is what my test look like:
const fromEventMock = jest.spyOn(rxjs, 'fromEvent').mockReturnValue(of({ data: 123 }));
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [SomeModule],
declarations: [
MyComponent,
],
providers: [
{
provide: WindowRef,
useValue: {
nativeWindow: {
document: {
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
},
},
},
},
],
schemas: [NO_ERRORS_SCHEMA],
});
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
The mock of fromEvent is working as expected. I tried multiple mock strategy but the problem seems to occur before that.
I tried mocking the WindowRef, not mocking it. Same thing for fromEvent.
Does anyone had that problem before? What am I missing here?