document.addEventListender测试无法通过Jest和Enzyme使用

时间:2018-12-28 06:43:03

标签: javascript reactjs jestjs enzyme

示例组件:

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()无法运行...

0 个答案:

没有答案