【问题标题】:React/Jest - How to mock the behavior of event.preventDefault and event.stopPropagationReact/Jest - 如何模拟 event.preventDefault 和 event.stopPropagation 的行为
【发布时间】:2022-02-10 17:57:38
【问题描述】:

我有一个输入字段如下:

<Input name="score" type="number" className={cx(['input-width'])} value={this.state.score} isIncomplete={false} isInvalid={this.state.isScoreInvalid} min="0" max="100" onKeyPress={this.handleInput} onChange={this.updateValue} onBlur={this.updateScoreInvalidState} />

下面的函数被调用 OnKeypress

handleInput(event) {
    const charCode = (typeof event.which === 'number') ? event.which : event.keyCode;

    if (charCode === 45 || charCode === 46) {
      console.log("Here-------------");
      event.preventDefault();
      event.stopPropagation();
    }
  }

下面的函数被调用 onChange

updateValue(event) {
    this.setState({ [event.target.name]: event.target.value });
}

我想测试这种行为: 如果输入无效:'-' OR '.' 忽略输入并且不更新状态变量得分。 进行以下测试。

it('should render input field correctly with invalid character as input', () => {
    const wrapper = shallowWithIntl(<TestView {...testProps} />).first().shallow();
    const score = wrapper.find('Input[name="score"]');
    const onKeypressEvent = {
      preventDefault: jest.fn(),
      stopPropagation: jest.fn(),
      which: 45,
      target: { name: 'score', value: '-' },
    };
    const onChangeEvent = {
      target: { name: 'score', value: '-' },
    };

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);

    score.simulate('keypress', onKeypressEvent);
    score.simulate('change', onChangeEvent);
    wrapper.update();

    expect(wrapper.state('score')).toEqual(5);
    expect(wrapper.state('isScoreInvalid')).toEqual(false);
  });

测试未按预期工作。它并没有阻止事件发生。

如何测试这个功能?谢谢!

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:
    const event = {
        preventDefault: jest.fn(),
        clipboardData: {
          getData: () => pasteValue,
        },
      } as unknown as React.ClipboardEvent<HTMLInputElement>;
    

    【讨论】:

    • 请不要发布仅代码的答案。未来的读者会很高兴看到解释为什么它回答了这个问题,而不是必须从代码中推断出来。
    • 没时间解决他的问题,但想帮助他展示我如何在 typescript 中模拟事件、preventDefault 和其他人,做出反应,但你是对的
    猜你喜欢
    • 2013-08-11
    • 2011-08-23
    • 2019-11-02
    • 2017-02-23
    • 1970-01-01
    • 2022-06-28
    • 2017-06-08
    相关资源
    最近更新 更多