[英]How to test addEventListener in Mocha/Chai/Sinon with vanillajs and nodejs?
I have an issue with Mocha testing an eventlistener that checks for input. 我在Mocha测试用于检查输入的事件监听器时遇到问题。 My environment is with plain javascript, nodejs and mocha/chai/sinon for testing.
我的环境是使用普通的javascript,nodejs和mocha / chai / sinon进行测试。 I wrote some other tests that are working, basically checking functions but the test hits on "Cannot read property 'addEventListener' of null".
我编写了一些其他有效的测试,基本上检查了功能,但是测试命中“无法读取null的属性'addEventListener'”。
Since I'm quite new to testing I've dug around in the documentation, added JSDOM and such but no luck. 由于我对测试还很陌生,因此我在文档中进行了研究,因此添加了JSDOM等等,但是没有运气。 I simply don't know how to check for the eventlistener.
我根本不知道如何检查事件监听器。 Many of the threads already available are React environments which seem to have some sort of built in applications that helps them, but not me.
React环境已经提供了许多可用的线程,其中似乎有某种内置的应用程序可以帮助他们,但我却没有。
So it's basically this, really narrowed down: 所以基本上是这样,真正缩小了范围:
const userInput = document.querySelector("#userInfo");
userInput.addEventListener("input", changeContent);
It checks for user input and in the changeContent method it just checks for length etc. Any takers on how I should do this? 它检查用户输入,并在changeContent方法中检查长度等。是否有人应如何做?
Edit: Slight workaround that "skips" my issue, but it would be nice to learn how to solve it in a test anyway. 编辑:可以“跳过”我的问题的小解决方法,但是无论如何要在测试中学习如何解决它会很好。 With this the test passes (because it ignores it).
测试通过(因为它忽略了它)。
Workaround, since the test points eventListener to null: 解决方法,因为测试将eventListener指向null:
if(userInput){
userInput.addEventListener("input", changeContent)
}
You can use a spy
to test if addEventListener
is getting called. 您可以使用
spy
来测试是否调用了addEventListener
。 There is no specific reason to test the implementation of addEventListener
. 没有特定的理由来测试
addEventListener
的实现。
Also you have to fake the document.querySelector
and force it to return an HTMLElement. 另外,您还必须伪造
document.querySelector
并强制其返回HTMLElement。
Long story short: 长话短说:
Use spy for addEventListener
: https://sinonjs.org/releases/v7.3.2/spies/ 将间谍用于
addEventListener
: https : //sinonjs.org/releases/v7.3.2/spies/
Use fakes for document.querySelector
: https://sinonjs.org/releases/v7.3.2/ 对
document.querySelector
使用伪造品: https : //sinonjs.org/releases/v7.3.2/
Example of spy for console.log
: 监视
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.