Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest testing react component with react-intersection-observer

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

like image 662
Rafael Simões Avatar asked Jul 12 '19 13:07

Rafael Simões


2 Answers

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.

like image 131
Matthew Hill Avatar answered Sep 21 '22 13:09

Matthew Hill


Having same issue with Component that using IntersectionObserver.

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

import 'intersection-observer';

like image 37
omdjin Avatar answered Sep 23 '22 13:09

omdjin