使用 Sinon 测试 JavaScript 点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24038709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing JavaScript Click Event with Sinon
提问by tpgmartin
I am trying to produce some test to be able to better understand how to test DOM events with the combination of Mocha, Chai, Sinon and jQuery. I want to check that the alert function is correctly triggered on a click of the div element. I know that the setup of the HTML element is correct jQuery, but I'm not entirely sure how to produce a passing test for the code below. What's particularly strange is that I get a dialogue appearing on opening the HTML file in my browser, so I know the line '$('#thingy').trigger('click')' is doing what I'd expect. I am currently getting the following, 'TypeError: object is not a function'
我正在尝试进行一些测试,以便能够更好地了解如何结合使用 Mocha、Chai、Sinon 和 jQuery 来测试 DOM 事件。我想检查是否在单击 div 元素时正确触发了警报功能。我知道 HTML 元素的设置是正确的 jQuery,但我不完全确定如何为下面的代码生成通过测试。特别奇怪的是,我在浏览器中打开 HTML 文件时出现一个对话框,所以我知道 '$('#thingy').trigger('click')' 这行正在做我所期望的。我目前得到以下信息,'TypeError: object is not a function'
Relevant section from my test file, tests.js
我的测试文件中的相关部分,tests.js
describe('DOM tests - div element', function() {
$("body").append("<div id='thingy'>hello world</div>")
$('#thingy').attr('class', 'thingy');
$('#thingy').click(function() { alert( "I've been clicked!" ); });
it('should have called alert function', function () {
var spy = sinon.spy(alert);
$('#thingy').trigger('click')
sinon.assert(spy.called);
});
My HTML file is fairly standard, index.html
我的 HTML 文件相当标准,index.html
<!doctype html>
<html>
<head>
<title>Tests</title>
<link rel="stylesheet" href="mocha.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script src="chai.js"></script>
<script src="sinon-1.10.2.js"></script>
<script>
mocha.ui('bdd');
mocha.reporter('html');
var expect = chai.expect;
</script>
<script src="tests.js"></script>
<script>
mocha.run();
</script>
</body>
采纳答案by Pavling
You're not actually calling an alert
function, you're calling the window.alert
function, so you need to spy on that:
您实际上并不是在调用alert
函数,而是在调用window.alert
函数,因此您需要对其进行监视:
it('should have called alert function', function () {
var _savedAlert = window.alert;
try {
var spy = sinon.spy(window, 'alert');
$('#thingy').trigger('click');
sinon.assert.called(spy);
}
finally { window.alert = _savedAlert; }
});