jeudi 9 janvier 2020

How do I test an onScroll event with jest/enzyme - Reactjs

I am new to testing and can't figure out on how to test my component, my onScrollMock is not being fired with the code below, I'm using, jest and enzyme. please help.

I am not sure on how to approach the condition inside the handleScroll as well, test-coverage's pointing on that function.

StoryCardList.js

const handleScroll = (e) => {
const { scrollWidth, scrollLeft, clientWidth } = e.target;
const rightEnd = scrollWidth - scrollLeft === clientWidth;

if (rightEnd) {
  setAnimation(true);
} else {
  setAnimation(false);
}
  };

  return (
    <div className="story-card-list" onScroll={(e) => handleScroll(e)}>
      {stories.map(({ id, title, heroImage }, index, sourceStories) => {
        if (index === stories.length - 1) {
          return lastStory(id, title, heroImage, index, sourceStories);
        }
        return renderStoryCards(id, title, heroImage, index, sourceStories);
      })}
    </div>
  );
}

test

  let wrapper;
  const onScrollMock = jest.fn();

  beforeEach(() => {
    wrapper = shallow(<StoryCardList stories={stories} onScroll={onScrollMock} transitionDuration='2' transitionTiming='2' />);
  })

  it('should render without crashing', () => {
    expect(wrapper).toMatchSnapshot();
    expect(wrapper.find(StoryCard)).toHaveLength(3);
  });

  it('should have scrollable div', () => {
    expect(onScrollMock).not.toHaveBeenCalled()
    window.dispatchEvent(new window.UIEvent('scroll', { detail: 0 }));
    expect(onScrollMock).toHaveBeenCalled()
  })

Aucun commentaire:

Enregistrer un commentaire