测试JavaScript单击使用Sinon的事件 [英] Testing JavaScript Click Event with Sinon

查看:76
本文介绍了测试JavaScript单击使用Sinon的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一些测试,以便能够更好地理解如何使用Mocha,Chai,Sinon和jQuery的组合来测试DOM事件。我想检查单击div元素时是否正确触发了警报功能。我知道HTML元素的设置是正确的jQuery,但我不完全确定如何为下面的代码生成传递测试。特别奇怪的是,我在浏览器中打开HTML文件时出现对话,所以我知道'$('#thingy')行。触发器('click')'正在做我期望的事情。我目前得到以下内容,'TypeError:对象不是函数'

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'

我的测试文件的相关部分,tests.js

Relevant section from my test file, 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);
});

我的HTML文件相当标准,index.html

My HTML file is fairly standard, 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>

推荐答案

你实际上没有调用 alert 函数,你正在调用 window.alert 函数,所以你需要监视:

You're not actually calling an alert function, you're calling the window.alert function, so you need to spy on that:

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; }
});

这篇关于测试JavaScript单击使用Sinon的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆