Testing code that uses an IntersectionObserver

None of the posted answered worked for me because of our configuration of TypeScript and React (tsx) we’re using. Here’s what finally worked:

beforeEach(() => {
  // IntersectionObserver isn't available in test environment
  const mockIntersectionObserver = jest.fn();
  mockIntersectionObserver.mockReturnValue({
    observe: () => null,
    unobserve: () => null,
    disconnect: () => null
  });
  window.IntersectionObserver = mockIntersectionObserver;
});

Leave a Comment