Mocking IntersectionObserver in Jest

Aron Schüler Published


Table of Contents

Today, I tried to test a component in React which uses the HeadlessUI Dialog. Unfortunately, this test turned out to be rather hard, because the window object in jest tests gets (most commonly) generated by JSDOM and this in turn does not support layout utilities such as IntersectionObserver. The error message/stacktrace i got was the following:

Error: Uncaught [ReferenceError: IntersectionObserver is not defined]

Fixing the error

To do so, all that is really necessary is creating a new class and assign it both to window.IntersectionObserver and global.IntersectionObserver, so that node knows how to create an instance for this.

I did this by inserting the following snippet into my setupTests.ts file, but you could also do this on a test-level directly:

// Mock the IntersectionObserver, see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
export class IntersectionObserver {
  root = null;
  rootMargin = "";
  thresholds = [];
 
  disconnect() {
    return null;
  }
 
  observe() {
    return null;
  }
 
  takeRecords() {
    return [];
  }
 
  unobserve() {
    return null;
  }
}
window.IntersectionObserver = IntersectionObserver;
global.IntersectionObserver = IntersectionObserver;

Done!

With this snippet inserted, I was able to run my test without any problems. Hope this helped, let me know if it didn’t! 😊


Related Posts

Find posts on similar topics:


Support me via buymeacoffee

If I helped you solve a problem or you just like my content, consider supporting me by buying me a coffee.

Buy me a coffee

Comments