Ralitsa Velikova
Ralitsa Velikova

Reputation: 143

How do I test jQuery code with MochaJS?

I think, mocha does not recognise jQuery in the scope of my tests, because it tests plain JavaScript without a problem. I tried to require jQuery's full code in the beginning of the .js file with my tests, tried to manually define $ with before(function() {/* some code */}), but I always get this ReferenceError: $ is not defined when I try to run my tests and there is jQuery code tested with some of them.

Any ideas of how do I fix this?

Upvotes: 4

Views: 2572

Answers (1)

marsh
marsh

Reputation: 1441

In docs:

Mocha runs in the browser. Every release of Mocha will have new builds of ./mocha.js and ./mocha.css for use in the browser. To setup Mocha for browser use all you have to do is include the script, stylesheet, tell Mocha which interface you wish to use, and then run the tests. A typical setup might look something like the following, where we call mocha.setup('bdd') to use the BDD interface before loading the test scripts, running them onload with mocha.run().

So you can include any scripts, but the first you include libs, like jQuery, then tests

<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="mocha.css" />
</head>
<body>
  <div id="mocha"></div>
  <script src="jquery.js"></script>
  <script src="expect.js"></script>
  <script src="mocha.js"></script>
  <script>mocha.setup('bdd')</script>
  <script src="test.array.js"></script>
  <script src="test.object.js"></script>
  <script src="test.xhr.js"></script>
  <script>
    mocha.checkLeaks();
    mocha.globals(['jQuery']);
    mocha.run();
  </script>
</body>
</html>

Upvotes: 1

Related Questions