mardi 5 juillet 2016

Proper way of writing a unit test that involves the DOM

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
    toggleNavHandler(target, div);
    chai.assert.isTrue(div.classList.contains("toggle-bg"));
  });
  });
});

What would be a better way of writing this test?

Aucun commentaire:

Enregistrer un commentaire