I'm trying to test if an event has been added in the init method called by componentDidMount, but that event is going to be added only if a component's attribute is set in "true" so I want to spy on the addEventHandler method and call the "toBeCalledWith('eventName')" so I have something like this:
export interface IMyComponentProps{
flag?: boolean;
}
export class MyComponent extends Component<IMyComponentProps> {
private myProperty: HTMLElement;
public componentDidMount() {
this.init();
}
private init() {
if (this.props.flag) {
this.myProperty.addEventListener("event", arg2, arg3);
}
}
}
Then I have my test looking like this:
test("Test 1", () => {
const spyInit = jest.spyOn(MyComponent.prototype, "init");
wrapper = mount(
<MyComponent />
);
expect(spyInit).toBeCalled();
})
but the test above does not cover if the addEventListener is called or not so I'm trying different ways like following, without success:
const spyAddListener = jest.spyOn(MyComponent.prototype, "myProperty.addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.instance().myProperty, "addEventHandler");
const spyAddListener = jest.spyOn(MyComponent.prototype.myProperty, "addEventHandler");
any suggestion?