Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

javascript - Triggering event for unit testing

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...