Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest + React: IntersectionObserver mock not working?

In my component.test.js, I tried mocking the IntersectionObserver by doing something like this:

const mock = ()=>({
    observe: jest.fn(),
    disconnect: jest.fn()
});
window.IntersectionObserver = jest.fn().mockImplementation(mock);


describe("Component", ()=>{
    it("test 1", ()=>{
        render(<Component/>);
        ...
    }
});

My component.js looks something like this (it does that infinite pagination thing):

//ref to last item loaded >> load more items once it enters view
const observer = useRef();
const lastEntryRef = useCallback((node)=>{
        ...
        observer.current.disconnect(); //ERROR LINE
    }
    ...
);

When I run the tests, however, I get TypeError: observer.current.disconnect is not a function; same goes for observer.current.observe() if it runs. I tried testing it inside the it() block of component.test.js itself by instantiating an IntersectionObserver and then calling those methods and the same message showed when I re-ran the tests, so the errors look unrelated to how IntersectionObserver was set up in component.js. Am I not mocking IntersectionObserver correctly? If so, how do I fix it?

like image 847
dawg Avatar asked Nov 07 '25 17:11

dawg


1 Answers

I recommend you to replace the arrow function for a normal function because you need to use the new operator to create an InterceptionObserver object:

const mock =  function() {
  return {
    observe: jest.fn(),
    disconnect: jest.fn(),
  };
};

//--> assign mock directly without jest.fn
window.IntersectionObserver = mock;

The you can check if window.InterceptionObserver.observe has been called.

like image 150
lissettdm Avatar answered Nov 09 '25 06:11

lissettdm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!