1

I am trying to trigger a scroll event inside of my unit test using Mocha running in a browser. I have the following code:

describe('Background Change', function() {
  describe('toogleBgHandler()', function() {
  it('should contain toggle-bg when scrollTop is more than 0', function() {
    let html = document.createElement('html');
    var target = [];
    target.push(html);
    let body = document.createElement('body');
    let div = document.createElement('div');
    html.appendChild(body);
    body.appendChild(div);
    document.body.dispatchEvent(new Event("scroll"));
    toggleBgHandler(target, div)
    chai.assert.isTrue(div.classList.contains("toggle-bg"));
  });
  });
});

Function I am trying to test:

function toggleBgHandler(html, ele) {
        document.addEventListener("scroll", (e) => {
        if (html[0].scrollTop === 0) {
            ele.classList.remove("toggle-bg");
        } else {
            ele.classList.add("toggle-bg");
        }
      });
    }

How do I trigger a scroll event for a function that depends on it? I have also tried creating an event object, but that didn't work either. Any pointers would be great.

freetoplay
  • 657
  • 2
  • 8
  • 23

1 Answers1

1

Is the scroll event your code is looking for on the window or on an _element? If it's on the window, you should be able to dispatch a scroll event like this:

window.dispatchEvent(new Event('scroll'));

Else, you can do:

element.dispatchEvent(new Event('scroll'));

Here's a jsfiddle demonstrating.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • I just made an update to my code that reflects that change, but it's still not working for me for me some reason. – freetoplay Jul 06 '16 at 04:58
  • In your update, you're dispatching the event _before_ the event listener was added. You'll want to call `toggleBgHandler`, then dispatch the event, then assert. – Jacob Jul 06 '16 at 16:19
  • I have tried that as well, but it seems like the scroll event isn't being picked up as the code inside of the listener never gets called. – freetoplay Jul 06 '16 at 20:01