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
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.
Having same issue with Component that using IntersectionObserver.
Update: we need to import intersection-observer directly on test file.
import 'intersection-observer';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With