我正在使用 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/