如何测试调度自定义事件的方法

时间:2019-03-21 12:35:56

标签: javascript reactjs dom jestjs enzyme

我有一个静态方法来创建一个自定义事件并调度它:

def plotPeaks(peaks_pos, df, y, threshold):
    fig, ax = plt.subplots()
    fig.suptitle('Variance peaks')
    ax.set_ylabel('Calcium level')
    ax = df.plot(y='yvalue', c='r', ax=ax, label='Raw data' )
    ax2 = ax.twinx()
    ax2.set_ylabel('Variance value')
    df.plot(y=y, c='orange', ax=ax2, label='Variance')
    ax2.axhline(y=threshold, label='Threshold')
    df.iloc[peaks_pos].plot(style='.', y=y, c='blue', ax=ax2, label='Peaks')
    return fig

我正在尝试如下测试:

    class MyComponent extends {
       static refreshComponent() {
         const event = new Event('refreshComponent');
         document.dispatchEvent(event);
       }
       render() {
          MyComponent.refreshComponent();
       }
    }

但是在这里没有调用dispatchEvent,因为没有'new Event()'的模拟。有没有办法模拟它?请帮助

2 个答案:

答案 0 :(得分:1)

您可以像这样测试调度事件:

describe('refreshComponent', () => {
  it('should dispatch an event', () => {
    jest.spyOn(global, 'Event').mockImplementation((type: string, eventInit?: any) => ({ type, eventInit }));
    const mockDispatchEvent = jest.spyOn(document, 'dispatchEvent').mockImplementation(() => true);

    // render your component

    expect(mockDispatchEvent).toHaveBeenCalledWith({
      type: 'refreshComponent',
    });
  });
});

这种方式可以预期事件类型和事件初始化值。如果你不想期待细节事件,我们不需要模拟事件和期待:

expect(mockDispatchEvent).toHaveBeenCalledWith(expect.any(Event));

答案 1 :(得分:0)

您可以使用Jest模拟全局变量:

describe('your test', () => {
  let EventBak
  let documentBak

  beforeAll(() => {
    EventBak = global.Event
    documentBak = global.document
    global.Event = jest.fn()
    global.document = {
      ...global.document,
      dispatchEvent: jest.fn()
    }
  })

  afterAll(() => {
    global.Event = EventBak
    global.document = documentBak
  })

  it('...', () => {
    ...
    expect(global.document.dispatchEvent).toHaveBeenCalled()
  })
})