Testing JavaScript Click Event with Sinon

心不动则不痛 提交于 2019-12-23 07:46:44

问题


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'

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

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>


回答1:


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


来源:https://stackoverflow.com/questions/24038709/testing-javascript-click-event-with-sinon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!