JS is test code that uses IntersectionObserver

I have a (rather poorly written) javascript component in my application that handles page numbering with infinite scroll, and I'm trying to rewrite it to use IntersectionObserveras described here , however, I'm having problems testing.

Is there a way to control the observer behavior in the QUnit test, that is, to trigger the observer callback with some entries described in my tests?

A possible solution I found is to present a callback function in the component prototype and call it directly in my test, something like this:

InfiniteScroll.prototype.observerCallback = function(entries) {
    //handle the infinite scroll
}

InfiniteScroll.prototype.initObserver = function() {
    var io = new IntersectionObserver(this.observerCallback);
    io.observe(someElements);
}

//In my test
var component = new InfiniteScroll();
component.observerCallback(someEntries);
//Do some assertions about the state after the callback has been executed

, , IntersectionObserver , , , , , ?

, jQuery :)

+10
2

2019 , :

import ....

describe('IntersectionObserverMokTest', () => {
  ...
  const observeMock = {
    observe: () => null,
    disconnect: () => null // maybe not needed
  };

  beforeEach(async(() => {
    (<any> window).IntersectionObserver = () => observeMock;

    ....
  }));


  if(' should run the Test without throwing an error for the IntersectionObserver', () => {
    ...
  })
});

observe ( disconnect) IntersectionObserver . (.: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Browser_compatibility)

https://gist.github.com/ianmcnally/4b68c56900a20840b6ca840e2403771c, jest

+2

jest.setup.js IntersectionObserver :

global.IntersectionObserver = class IntersectionObserver {
  constructor() {}

  observe() {
    return null;
  }

  unobserve() {
    return null;
  }
};

Jest beforeAll, beforeEach.

0

Source: https://habr.com/ru/post/1678137/


All Articles