Reactjs 当使用pubsubs和Jest/Enzyme时,如何模拟React组件上的发布/订阅事件?
我有以下代码:Reactjs 当使用pubsubs和Jest/Enzyme时,如何模拟React组件上的发布/订阅事件?,reactjs,jestjs,publish-subscribe,enzyme,Reactjs,Jestjs,Publish Subscribe,Enzyme,我有以下代码: 类虚拟扩展React.Component{ 建造师(道具){ this.state={field:'} } componentDidMount(){ PubSub.subscribe('事件',()=>{ this.setState({field:'a'}); }); } } 我想确保发布事件时,状态设置为a。如何使用Jest with Ezyme实现这一点?PubSub提供了publish()和publishSync(): publishSync() publish()
类虚拟扩展React.Component{
建造师(道具){
this.state={field:'}
}
componentDidMount(){
PubSub.subscribe('事件',()=>{
this.setState({field:'a'});
});
}
}
我想确保发布
事件时,状态设置为a
。如何使用Jest with Ezyme实现这一点?PubSub提供了publish()
和publishSync()
:
publishSync()
publish()
您可以使用publishSync()
或将假计时器与publish()
配合使用
publishSync()
test('应该订阅事件',()=>{
常量分量=浅();
expect(component.state('field')).toBe('');
PubSub.publishSync(“事件”);
expect(component.state('field')).toBe('a');
});
publish()
和Jest
:
test('应该订阅事件',()=>{
jest.useFakeTimers();//在模拟中包装计时器函数
常量分量=浅();
expect(component.state('field')).toBe('');
PubSub.publish(“事件”);
jest.runAllTimers();//运行所有计时器回调
expect(component.state('field')).toBe('a');
});
PubSub在自己的测试中同时使用和。嘿,Brian,你能告诉我或回答我如何在角度上下文中解决相同的问题吗