繁体   English   中英

如何使用vanillajs和nodejs在Mocha / Chai / Sinon中测试addEventListener?

[英]How to test addEventListener in Mocha/Chai/Sinon with vanillajs and nodejs?

我在Mocha测试用于检查输入的事件监听器时遇到问题。 我的环境是使用普通的javascript,nodejs和mocha / chai / sinon进行测试。 我编写了一些其他有效的测试,基本上检查了功能,但是测试命中“无法读取null的属性'addEventListener'”。

由于我对测试还很陌生,因此我在文档中进行了研究,因此添加了JSDOM等等,但是没有运气。 我根本不知道如何检查事件监听器。 React环境已经提供了许多可用的线程,其中似乎有某种内置的应用程序可以帮助他们,但我却没有。

所以基本上是这样,真正缩小了范围:

const userInput = document.querySelector("#userInfo");
userInput.addEventListener("input", changeContent);

它检查用户输入,并在changeContent方法中检查长度等。是否有人应如何做?

编辑:可以“跳过”我的问题的小解决方法,但是无论如何要在测试中学习如何解决它会很好。 测试通过(因为它忽略了它)。

解决方法,因为测试将eventListener指向null:

if(userInput){
  userInput.addEventListener("input", changeContent)
}

您可以使用spy来测试是否调用了addEventListener 没有特定的理由来测试addEventListener的实现。

另外,您还必须伪造document.querySelector并强制其返回HTMLElement。

长话短说:

将间谍用于addEventListenerhttps : //sinonjs.org/releases/v7.3.2/spies/

document.querySelector使用伪造品: https : //sinonjs.org/releases/v7.3.2/

监视 console.log 示例

// method implementend in your project
function log() {
   console.log('Hello world');

}

// log.spec.ts

...
describe('whatever test suite', () => {
    it('test log', () => {
        const consoleSpy = Sinon.spy(console, 'log');
        log();

        Sinon.assert.calledWith(consoleSpy, 'Hello world');
    });
});
...

暂无
暂无

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

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