简体   繁体   English

单元测试的触发事件

[英]Triggering event for unit testing

I am trying to trigger a scroll event inside of my unit test using Mocha running in a browser. 我正在尝试使用在浏览器中运行的Mocha在单元测试中触发滚动事件。 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. 任何指针都很棒。

Is the scroll event your code is looking for on the window or on an _element? 您的代码正在窗口或_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. 这是一个jsfiddle演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM