30

I'm trying to test a component that has a child component that includes react-intersection-observer but I always get an error

I tried to import the library but it still fails. This the initial test

    beforeEach(() => {
      testContainer = document.createElement("div");
      document.body.appendChild(testContainer);
      subject = memoize(() =>
        mount(<FilterNav {...props} />, { attachTo: testContainer })
      );
    });

    afterEach(() => {
      testContainer.remove();
    });

    context("the main filter is shown initially", () => {
      it("sets focus on the primary filter", () => {
        subject();
        const input = testContainer.querySelector(".main-input");
        expect(document.activeElement).toEqual(input);
      });

I'm getting this error -> Uncaught [ReferenceError: IntersectionObserver is not defined]

Is there a way I can mock IntersectionObserver?

Thanks

0

7 Answers 7

34

you can do something like this in mock file(i called it intersectionObserverMock.js for exmple):

const intersectionObserverMock = () => ({
     observe: () => null
})
window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverMock);

and in the test file import the file directly like this:

import '../__mocks__/intersectionObserverMock';

this will solve youre "IntersectionObserver is not defined" issue

3
  • 1
    This worked for me in combination with declaring an Window interface like this: github.com/Microsoft/TypeScript/issues/… declare global { interface Window { IntersectionObserver: typeof IntersectionObserver } } Commented Oct 7, 2020 at 14:02
  • 1
    Minor addition to this is to also add other functions that you are using on observer. In my case I had to add disconnect: () => null because I used observer.disconnect() in my code
    – metodribic
    Commented May 11, 2023 at 8:15
  • These alone didnt work for me. I also had to update my jest.config.js file to include the mocked IntersectionOberserver file in my setupFiles like this: javascript ... setupFiles: ['<rootDir>/src/test/mocks/localStorage.mock.js', '<rootDir>/src/__mocks__/intersectionObserverMock.js'], ...
    – Cat Perry
    Commented Aug 29 at 18:03
21

Having same issue with Component that using IntersectionObserver.

Update: we need to import intersection-observer directly on test file.

import 'intersection-observer';

1
  • 4
    Thanks, this worked for me. npm i --save-dev intersection-observer
    – epsilon42
    Commented Dec 10, 2020 at 8:35
15

The only thing that worked for me, create a file src\__mocks__\intersectionObserverMock.js

global.IntersectionObserver = class IntersectionObserver {
  constructor() {}

  observe() {
    return null;
  }

  disconnect() {
    return null;
  };

  unobserve() {
    return null;
  }
};

In your test import file:

import './__mocks__/intersectionObserverMock'
14

Create a mock in your setupTests file:

// Mock IntersectionObserver
class IntersectionObserver {
  observe = jest.fn()
  disconnect = jest.fn()
  unobserve = jest.fn()
}

Object.defineProperty(window, 'IntersectionObserver', {
  writable: true,
  configurable: true,
  value: IntersectionObserver,
})

Object.defineProperty(global, 'IntersectionObserver', {
  writable: true,
  configurable: true,
  value: IntersectionObserver,
})

This will sort it not being defined.

1
  • This worked great, thank you! :) I had to add disconnect for my use case, edited answer to add it. Commented Jun 6, 2021 at 9:27
6

To fix this issue I'd recommend using mockAllIsIntersecting from test-utils.js in react-intersection-observer. This function mocks the IntersectionObserver.

e.g.

import { mockAllIsIntersecting } from 'react-intersection-observer/test-utils';

it("sets focus on the primary filter", () => {
    subject();
    mockAllIsIntersecting(true);

    const input = testContainer.querySelector(".main-input");
    expect(document.activeElement).toEqual(input);
  });
1
  • 3
    This worked for me. Thanks! No need to mock IntersectionObserver yourself. The test-utils already does it for you. Commented May 12, 2022 at 20:50
3

I actually was able to solve this issue with a mock function and include it in the window object

const observe = jest.fn();

window.IntersectionObserver = jest.fn(function() {
  this.observe = observe;
});
1

I extended Teebu's solution to trigger a first intersecting element. My test then act as if the intersection would match.

global.IntersectionObserver = class IntersectionObserver {

  constructor(private func, private options) {}

  observe(element: HTMLElement) {
    this.func([{isIntersecting: true, target: element}]);
  }

  disconnect() {
    return null;
  };

  unobserve() {
    return null;
  }
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.