React Testing Library TypeError: Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 1 present

Viewed 6040

i have react class component that have event

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');
  }

this component used in functional component, when i test the functional component there is error message enter image description here

i am using React Testing Library for test this, i already searched on google but not yet found solution for this, please help me. if there is any way to mock the removeEventListener on react testing library or Jest. thanks in advance.

2 Answers

The removeEventListener needs two arguments, type and listener. type specifies the type of event for which to remove an event listener and listener is the EventListener function of the event handler to remove from the event target.

So try to put a null in the place of listener like this

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

Hope it works.

alfan-juniyanto,

The error message tells you exactly what's wrong -- your call to the method removeEventListener('scroll'), in your componentWillUnmount() function, is expecting two parameters:

  1. The event to stop listening to,
  2. The current event handler that you had previously registered when you called addEventListener (which doesn't appear to be in the code snippet you supplied).

For more information, you can read here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

However, to specifically answer your question, you should pass a pointer to the event handler that you used in the addEventListener cycle.

If you just want to make this error message stop for the purposes of your test, you could do something like this:

componentWillUnmount() {
    const _fnEmptyFunctionPointer = ()=>{};
    this.monthRef.current.removeEventListener('scroll', _fnEmptyFunctionPointer);
    this.yearRef.current.removeEventListener('scroll', _fnEmptyFunctionPointer);
  }

The code snippet I provided above simply just passes an empty function as the second (required) parameter for the removeEventListener method (really however, like I said previously, you should be passing the pointer to the original function you registered for the listener).

Hope this helps at least explain whats going on with that error you recieved.

Good luck!

Related