将 PubSubJS 与 Jest/Enzyme 一起使用时如何模拟 React 组件上的 Publish/subscribe 事件?
How to mock Publish/subscribe events on React Components when using PubSubJS with Jest/Enzyme?
我有以下代码:
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()
and publish()
with Sinon
fake timers。
我有以下代码:
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()
callsdeliver()
synchronously.publish()
usessetTimeout()
.
您可以使用 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()
and publish()
with Sinon
fake timers。