我有以下代码:
class Dummy extends React.Component {
constructor(props) {
this.state = { field: '' }
}
componentDidMount() {
PubSub.subscribe('event', () => {
this.setState({ field: 'a' });
});
}
}
我想确保当我发布event
时,状态设置为a
。如何使用Jest with Enzyme实现这一目标?
PubSub提供publish()
和publishSync()
:
publishSync()
calls deliver()
synchronously。publish()
uses setTimeout()
。您可以使用publishSync()
或使用publish()
假冒计时器。
publishSync()
test('should subscribe to event', () => {
const component = shallow(<Dummy />);
expect(component.state('field')).toBe('');
PubSub.publishSync('event');
expect(component.state('field')).toBe('a');
});
publish()
和Jest
Timer Mocks:
test('should subscribe to event', () => {
jest.useFakeTimers(); // wrap timer functions in mocks
const component = shallow(<Dummy />);
expect(component.state('field')).toBe('');
PubSub.publish('event');
jest.runAllTimers(); // run all timer callbacks
expect(component.state('field')).toBe('a');
});
PubSub在自己的测试中使用publishSync()
和publish()
with Sinon
fake timers。