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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…