我正在使用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');
});
});
答案 0 :(得分:1)
所以你必须像这样嘲笑'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()
});
});