Pablo Jurado

06 July, 2022

How to mock the Intersection Observer API

We might need to mock the Intersection Observer API when testing our components

In my previous post, I demonstrated how to create an infinite scroll component utilizing the Intersection Observer API. When testing the component we will get the following error ReferenceError: IntersectionObserver is not defined.

To avoid this error, we need to mock the Observer API like so:

  beforeEach(() => {
    const mockIntersectionObserver = jest.fn();
    window.IntersectionObserver = mockIntersectionObserver.mockReturnValue({
      observe: jest.fn(),
      unobserve: jest.fn(),
      disconnect: jest.fn(),
    });
  });