0

I am very new to unit testing. I would like some pointers on how to properly write a test that involves the DOM and callbacks. I have been reading materials online, but I am still confused on a few parts.

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

I am in the process of writing a test in Mocha that looks like this (this is my first test case and it's unfinished). I have read that I shouldn't include DOM elements in the test.

describe('Background Change', function() {
  describe('toogleBgHandler()', function() {
  it('should contain toggle-bg when scrollTop is more than 0', function() {
    let target = [{scrollTop : 10}];
    let div = document.createElement('div');
    // need to trigger scroll event here
    toggleBgHandler(target, div);
    chai.assert.isTrue(div.classList.contains("toggle-bg"));
  });
  });
});

What would be a better way of writing this test?

freetoplay
  • 657
  • 2
  • 8
  • 23
  • 1
    This seems fine. The code is supposed to modify a DOM element so I think you'd need to include one. Either a headless browser with mocha as you're doing or actually execute the test in a brower using Qunit or similar.You might step up a bit and trigger a scroll event (instead of calling toggleNavHandler directly) then check whether the class is added. – prototype Jul 06 '16 at 02:50
  • What @prototype said. Just a note, you can run mocha in the browser as well. – Vadim Jul 06 '16 at 03:57

0 Answers0