I'm trying to mock an event handler from the arcgis js library using jest, but am having trouble getting a reference to the handler and triggering the callback function. I decided to mock the event handler using node's built-in events module but when I emit the event, the callback is never entered.
foo.ts
createSomething(
onComplete: fooCompleteCallback
): void {
if (this.isReady()) {
const handler = foo.addEventHandler((event) => {
if (event.state === EVENT_COMPLETE) {
handler.remove();
onComplete(event.graphic);
}
});
foo.create();
}
}
foo.test.ts
import events from 'events';
class foo {
eventEmitter = new events.EventEmitter();
addEventHandler = () => this.eventEmitter.on('complete', (callback) => callback({state: 'complete'}));
isReady = jest.fn().mockImplementation(() => true);
create = () => this.eventEmitter.emit('complete');
}
export default new foo();
I was pretty close, here is what the correct test code looks like
foo.test.ts
class foo {
eventEmitter = new events.EventEmitter();
handler = { remove: jest.fn() }
fooEvent = {
state: 'complete'
}
addEventHandler = (callback) => {
this.eventEmitter.on('complete', () => callback(this.sketchEvent));
return this.handler;
};
create = (createOptions) => { this.eventEmitter.emit('complete') };
}
export default new foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With