title: How to trigger a Pubsub.js event in a jest test for react.js
body: <p>I am implementing internationalization in a react application with the <a href="https://github.com/yahoo/react-intl" rel="nofollow noreferrer">react-intl</a> library. The language can be triggered in different components, so I used the <a href="https://github.com/mroderick/PubSubJS" rel="nofollow noreferrer">pubsub-js</a> library to publish an event each time the language is changed, and subscrib to this event in my central App Component, which then switches the locale and messages which are displayed in the whole application. </p>
  
  <p>My question concerns writing tests with <a href="https://facebook.github.io/jest/" rel="nofollow noreferrer">jest</a> and <a href="https://github.com/airbnb/enzyme" rel="nofollow noreferrer">enzyme</a> which would trigger the language change and have my App component updated with the language, so I can assert that the state variables dealing with the locale are correctly updated. Is it possible to trigger such events, or am I on a wrong path here? My code is listed below</p>
  
  <pre><code>//Relevant parts of the app component
  
  
  class App extends Component {
    constructor(props) {
      super(props);
      this.localeStore = new LocaleStore();
      this.state = {
        locale: this.localeStore.locale(),
        messages: this.localeStore.messages()
      };
    }
  
    componentDidMount() {
      PubSub.subscribe(LocaleEvent.change, (event, locale) =&gt; {
        this.setState({locale: locale.code, messages: locale.messages})
      });
    }
  
    componentWillUnmount() {
      PubSub.unsubscribe(LocaleEvent.change);
    }
  
    render() {
      return (
        &lt;IntlProvider key={ this.state.locale } locale={ this.state.locale } messages={ this.state.messages }&gt;
          &lt;div&gt;
            ...
          &lt;/div&gt;
        &lt;/IntlProvider&gt;
      );
    }
  }
  
  // App.test.js
  
  describe('App', () =&gt; {
    it('renders without crashing', () =&gt; {
      const div = document.createElement('div');
      mount(&lt;App /&gt;);
    });
  
    // This test fails, because the event is not published and the state does not change
    it('correctly switches the language when the language change event is triggered', () =&gt; {
      let app = mount(&lt;App /&gt;);
  
      PubSub.publish('locale.change', {code: 'en', messages: {}});
  
      expect(app.state().locale).toEqual('en');
    });
  });
  </code></pre>