Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test handler with jest?

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();
like image 675
I Like Avatar asked Oct 24 '25 06:10

I Like


1 Answers

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();
like image 74
I Like Avatar answered Oct 26 '25 00:10

I Like



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!