示例组件:
class Modal extends Component {
componentDidMount() {
document.addEventListener('keydown', this.onEscPress, false);
}
componentWillUnmount() {
document.addEventListener('keydown', this.onEscPress, false);
}
@bind onEscPress(event) {
if (event.keyCode === 27) {
this.props.onClose();
}
}
render() {
<div className=".modal">...</div>
}
}
我的测试:
const closeModal = jest.fn();
const wrapper = shallow(<Modal onClose={closeModal} />);
it('executes the `onClose` function when `esc` key is pressed', () => {
const modal = wrapper.find('.modal');
modal.simulate('keydown', { keyCode: 27 });
expect(closeModal).toBeCalled();
});
但是我的测试失败了,因为closeModal()
无法运行...