如何在使用带有Jest / Enzyme的PubSubJS时模拟在React组件上发布/订阅事件?

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

我有以下代码:

class Dummy extends React.Component {
  constructor(props) {
    this.state = { field: '' }
  }

  componentDidMount() {
    PubSub.subscribe('event', () => {
      this.setState({ field: 'a' });
    });
  }
}

我想确保当我发布event时,状态设置为a。如何使用Jest with Enzyme实现这一目标?

reactjs jestjs publish-subscribe enzyme
1个回答
1
投票

PubSub提供publish()publishSync()

您可以使用publishSync()或使用publish()假冒计时器。


publishSync()

test('should subscribe to event', () => {
  const component = shallow(<Dummy />);
  expect(component.state('field')).toBe('');
  PubSub.publishSync('event');
  expect(component.state('field')).toBe('a');
});

publish()Jest Timer Mocks

test('should subscribe to event', () => {
  jest.useFakeTimers();  // wrap timer functions in mocks

  const component = shallow(<Dummy />);
  expect(component.state('field')).toBe('');

  PubSub.publish('event');
  jest.runAllTimers();  // run all timer callbacks

  expect(component.state('field')).toBe('a');
});

PubSub在自己的测试中使用publishSync()publish() with Sinon fake timers

© www.soinside.com 2019 - 2024. All rights reserved.