如何用 jest 测试 handler?

问题描述 投票:0回答:1

我正在尝试使用 jest 模拟 arcgis js 库中的事件处理程序,但无法获取对处理程序的引用并触发回调函数。我决定使用节点的内置

events
模块来模拟事件处理程序,但是当我发出事件时,永远不会输入回调。

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();
events jestjs handler
1个回答
3
投票

我已经非常接近了,这是正确的测试代码的样子

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();
© www.soinside.com 2019 - 2024. All rights reserved.