React 测试库类型错误:无法在“EventTarget”上执行“removeEventListener”:需要 2 个参数,但仅存在 1 个

Ahm*_*nto 1 reactjs jestjs react-testing-library

我有一个有事件的反应类组件

constructor(props) {
    super(props);

    this.monthRef = React.createRef();
    this.yearRef = React.createRef();

    this.state = {
      moIndexActive: props.initialMonth - 1,
      yeIndexActive: years.findIndex(y => y === `${props.initialYear}`),
    };
  }
//some code blablabla
// this error occur in this line bellow
  componentWillUnmount() {
    this.monthRef.current.removeEventListener('scroll');
    this.yearRef.current.removeEventListener('scroll');
  }
Run Code Online (Sandbox Code Playgroud)

该组件用于功能组件,当我测试功能组件时出现错误消息 在此输入图像描述

我正在使用 React 测试库来测试这个,我已经在谷歌上搜索过,但还没有找到解决方案,请帮助我。如果有任何方法可以模拟React测试库或Jest上的removeEventListener。提前致谢。

小智 10

需要removeEventListener两个参数,typelistenertype指定要删除事件侦听器的事件类型,并且 listener是要从事件目标中删除的事件处理程序的 EventListener 函数。

所以尝试把 a 放在这样的null地方listener

this.monthRef.current.removeEventListener('scroll',null)

希望它有效。