Search code examples
reactjsjestjspublish-subscribeenzyme

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?


Solution

  • PubSub provides publish() and publishSync():

    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.