dimanche 15 septembre 2019

How to mock/spy addEventListener method which is called on ref in ReactJS?

I am doing snapshot testing for one component which has ref on its div. The component looks like -

import React, { PureComponent } from 'react';

class SearchFlightBuilder extends PureComponent {

  scrollRef = React.createRef();

  state = {
    loading: true,
    error: false,
    filteredList: [],
    pageIndex: 0,
    scrollCalled: false,
  };


  handleScroll = (event) => {
    // make sure scroll should be called once
    if ((this.scrollRef.current.scrollTop + this.scrollRef.current.clientHeight >= this.scrollRef.current.scrollHeight) && !this.state.scrollCalled)  {
      this.setState({
          pageIndex: this.state.pageIndex + 1
      });
      this.setState({scrollCalled: true});
    }
  };

  componentDidMount = () => {
    this.scrollRef.current.addEventListener('scroll', this.handleScroll);
  };

  removeScrollEvent = () => {
    this.scrollRef.current.removeEventListener('scroll', this.handleScroll);
  };

  render() {

    return (
      <div className={c('Search-flight-builder')}  ref={this.scrollRef}>
        <p>Hello</P
      </div>
    );
  }
};

export default SearchFlightBuilder;

And testing file looks like this -

import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import SearchFlightBuilder from './SearchFlightBuilder';

configure({ adapter: new Adapter() });

const testFlightBuilder = () => <SearchFlightBuilder />;

describe('SearchFlightBuilder', () => {
  it('should render correctly', () => {
    const component = shallow(<SearchFlightBuilder />);
    expect(component).toMatchSnapshot();
  });


});


When I am running the tests, I am getting this error - TypeError: Cannot read property 'addEventListener' of null. I tried various approaches, but none of the approach works. Please help me here. I am using enzyme library here.

Aucun commentaire:

Enregistrer un commentaire