0

I have a component that uses @researchgate/react-intersection-observer, and I am trying to create a test where the component is visible.

When boiling my component down to only what is about the intersection-observer, it looks something like this:

import ReactIntersectionObserver from '@researchgate/react-intersection-observer';

export class MyComponent extends React.Component {

constructor(props) {
  super(props);

  this.state = { is_visible: false };
}

onItemIntersection = (e) => {
  if (e.isIntersecting) this.setState({ is_visible: true });
};

render = () => {
  return (
    <ReactIntersectionObserver
      onChange={this.onItemIntersection}
      disabled={this.state.is_visible}
    >
      {this.state.is_visible ? 'component shown' : 'placeholder shown'
    </ReactIntersectionObserver>
  );
};

I am then basically trying to create a test, with react testing library, that makes sure that is_visible gets set to true, but I can't figure out how to make sure that onChange gets called... (I have previously tested the component with enzyme, where I just would call onItemIntersection directly)

Currently my test looks like this:

import { mockIntersectionObserver } from '../test-utils';

describe('renders correctly', () => {

  const { IntersectionObserver } = window;
  beforeEach(() => {
    window.IntersectionObserver = mockIntersectionObserver;
  });

  afterEach(() => {
    window.IntersectionObserver = IntersectionObserver;
  });

  test('displaying placeholder', () => {
    const { container } = render(<MyComponent />);
    expect(container).toMatchSnapshot();
  });

  test('displaying component', () => {
    const { container } = render(<MyComponent />);

    // how to call onChange with { isIntersecting: true } ??
    expect(container).toMatchSnapshot();
  });

Where mockIntersectionObserver is defined as:

export const mockIntersectionObserver = jest.fn(() => ({
  root: () => null,
  observe: () => null,
  unobserve: () => null,
  disconnect: () => null
 }));
some_name
  • 389
  • 3
  • 17

0 Answers0