8

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>

2
  • Just a few minor things: Do you close the function in the describe's second parameter? Also, you're missing a semicolon after .append("<div id='thingy'>....</div>") and .trigger('click') Jun 4, 2014 at 13:39
  • Yes I do close the describe function, which isn't clear, and I've added the semicolons as suggested. Cheers
    – tpgmartin
    Jun 4, 2014 at 13:50

1 Answer 1

7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.