javascript - 如何在 react.js 的 Jest 测试中触发 Pubsub.js 事件

标签 javascript reactjs publish-subscribe jestjs enzyme

我正在使用 react-intl 在 React 应用程序中实现国际化图书馆。该语言可以在不同的组件中触发,所以我使用了 pubsub-js每次更改语言时发布事件的库,并在我的中央 App 组件中订阅此事件,然后切换区域设置和显示在整个应用程序中的消息。

我的问题涉及使用 jest 编写测试和 enzyme这将触发语言更改并使用该语言更新我的 App 组件,因此我可以断言处理语言环境的状态变量已正确更新。是否有可能触发此类事件,还是我走错了路?下面列出了我的代码

//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) => {
      this.setState({locale: locale.code, messages: locale.messages})
    });
  }

  componentWillUnmount() {
    PubSub.unsubscribe(LocaleEvent.change);
  }

  render() {
    return (
      <IntlProvider key={ this.state.locale } locale={ this.state.locale } messages={ this.state.messages }>
        <div>
          ...
        </div>
      </IntlProvider>
    );
  }
}

// App.test.js

describe('App', () => {
  it('renders without crashing', () => {
    const div = document.createElement('div');
    mount(<App />);
  });

  // 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', () => {
    let app = mount(<App />);

    PubSub.publish('locale.change', {code: 'en', messages: {}});

    expect(app.state().locale).toEqual('en');
  });
});

最佳答案

所以你必须像这样模拟 'pubsub-js' 模块:

import PubSub from 'pubsub-js'

jest.mock('pubsub-js', ()=>({
  subscribe:(e, fn) => fn({}, {code: 'de', messages:'someMessages'}),
  unsubscribe: jest.fn()
}))

describe('App', () => {

  it('correctly switches the language when the language change event is triggered', () => {
    const app = mount(<App />)
    expect(app.state().locale).toEqual('de');
    app.unmount()
    expect(PubSub.unsubscribe).toHaveBeenCalled()
  });
});

关于javascript - 如何在 react.js 的 Jest 测试中触发 Pubsub.js 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44024527/

相关文章:

javascript - Rails 上带有 selenium 的 chromedriver

javascript - 如何使用重置按钮删除选择选项标签中的背景颜色?

javascript - 水平滑动使用jquery ui

javascript - 如何通过ajax从php接收unicode字符串

c# - 我可以使用 Reactive Extensions 进行独立订阅/发布吗?

javascript - SVG 图像未在 ReactJS 中显示

javascript - 计算获胜者,取决于每个玩家的获胜机会

ReactJS 与 Django - 实际使用

security - Websphere MQ主题和SSL

go - 安排任务/消息以供以后处理/交付