asyarb / use-intersection-observer

Small React hook wrapper around the IntersectionObserver API.
MIT License
6 stars 3 forks source link

jsdom does not support IntersectionObserver #4

Open fabb opened 4 years ago

fabb commented 4 years ago

I tried to write tests for the callback, but it behaved weirdly in tests while working normally when running the application. Then I found out that jsdom does not do any layouting and therefore cannot support IntersectionObserver: https://github.com/jsdom/jsdom/issues/2032#issuecomment-340022412

Note that jsdom still does not do any layout or rendering, so this is really just about pretending to be visual, not about implementing the parts of the platform a real, visual web browser would implement.

So I ask myself:

  1. Why do the existing tests work at all?
  2. Would it be possible to use a mock IntersectionObserver instead of the polyfill to test every aspect of the hook thoroughly?
asyarb commented 4 years ago

You're totally right, the existing tests do not accurately represent the behavior of the browser scrolling down the page since we're using jsdom. At the time of writing, I hadn't had the time to set aside to figure out an appropriate solution for the tests so for now they're passing due to some unknown (to me anyway) snapshot weirdness.

In an ideal scenario, I think we would run our tests in some headless browser environment such as karma to throughly test the hook. I'm open to suggestions on this though!

I should have some time this coming weekend to work on this, so I'll keep this thread updated with any progress.

fabb commented 4 years ago

Yeah, a real end-to-end test with a real intersection observer based on layouting would be best, but maybe it would be good enough to mock it? That would still allow to test every aspect of the hook, even when more greybox testing than blackbox testing. It would even be possible to test that the hook disconnects correctly from the intersection observer when the ref or element changes.

This mock looks interesting: https://github.com/Shopify/quilt/blob/master/packages/jest-dom-mocks/src/intersection-observer.ts