Testing JavaScript Click Event with Sinon

I am trying to prepare some kind of test in order to better understand how to test DOM events with a combination of Mocha, Chai, Sinon and jQuery. I want to check that the warning function is triggered correctly by clicking on the div element. I know that setting the HTML element is correct for jQuery, but I'm not quite sure how to create a test pass for the code below. It is especially strange that I open a dialog that opens an HTML file in my browser, so I know the line '$ (' # thingy '). Trigger ('click') "does what I expect. Currently I get 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 pretty 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> 

+8
javascript mocha bdd chai sinon
Jun 04 '14 at 13:25
source share
1 answer

In fact, you are not calling the alert function, you are calling the window.alert function, so you need to monitor it:

 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; } }); 
+7
Jun 04 '14 at 21:21
source share



All Articles