JS - Testing code that uses an IntersectionObserver
In your jest.setup.js file, mock the IntersectionObserver with the following implementation:
global.IntersectionObserver = class IntersectionObserver {
constructor() {}
disconnect() {
return null;
}
observe() {
return null;
}
takeRecords() {
return null;
}
unobserve() {
return null;
}
};
Instead of using the Jest Setup File, you can do this mocking also directly in your tests or in your beforeAll,beforeEach blocks.
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;
});