JS - Testing code that uses an IntersectionObserver

前端 未结 6 1656
死守一世寂寞
死守一世寂寞 2020-12-18 17:57

I have a (rather poorly written) javascript component in my application that handles infinite scroll pagination, and i\'m trying to rewrite it to use the IntersectionO

6条回答
  •  星月不相逢
    2020-12-18 18:35

    Same problem in 2019 this is how I solved it:

    import ....
    
    describe('IntersectionObserverMokTest', () => {
      ...
      const observeMock = {
        observe: () => null,
        disconnect: () => null // maybe not needed
      };
    
      beforeEach(async(() => {
        ( window).IntersectionObserver = () => observeMock;
    
        ....
      }));
    
    
      if(' should run the Test without throwing an error for the IntersectionObserver', () => {
        ...
      })
    });
    

    So I create a mock object, with the observe (and disconnect) method and overwrite the IntersectionObserver on the window object. Depending on your usage, you might have to overwrite other functions (see: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility )

    The code is inspired by https://gist.github.com/ianmcnally/4b68c56900a20840b6ca840e2403771c but doesn't use jest

提交回复
热议问题