Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing JavaScript Click Event with Sinon

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>

like image 679
tpgmartin Avatar asked Jun 04 '14 13:06

tpgmartin


1 Answers

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; }
});
like image 190
Pavling Avatar answered Oct 15 '22 20:10

Pavling