Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Publish/subscribe events on React Components when using PubSubJS with Jest/Enzyme?

I have the following code:

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

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

I want to make sure that when I Publish event, the state is set to a. How do I achieve this using Jest with Enzyme?

like image 922
Sagar B Hathwar Avatar asked Oct 28 '25 17:10

Sagar B Hathwar


1 Answers

PubSub provides publish() and publishSync():

  • publishSync() calls deliver() synchronously.
  • publish() uses setTimeout().

You can either use publishSync() or use fake timers with 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() and 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 uses both publishSync() and publish() with Sinon fake timers in its own tests.

like image 119
Brian Adams Avatar answered Oct 31 '25 08:10

Brian Adams