layout | title | class | date |
---|---|---|---|
post |
Testing in the Browser |
client |
2015-09-03 17:00:00 -0700 |
We've written BDD-style tests in node, but sometimes we need to run tests in the browser as well. Mocha can be run in your browser by including 6 ingredients in an HTML file:
- The module you want to test
- The mocha and chai libraries
- An empty div with an id of 'mocha' (to hold the test output)
- A script which calls
mocha.setup('bdd')
- Any modules containing your tests
- A script which calls
mocha.run()
Below is an example HTML file for testing a module named mycode.js
with a testing file called mycode-test.js
. You may need to adjust the path names depending on your directory structure.
{% highlight html %}
<title>Browser tests</title> <script src="mycode.js"></script> <script src="../node_modules/mocha/mocha.js"></script> <script src="../node_modules/chai/chai.js"></script> <script>mocha.setup('bdd')</script> <script src="test/mycode-test.js"></script> <script> mocha.checkLeaks(); mocha.run(); </script> {% endhighlight %}GUI code often use pre-compiled templates to render repeated patterns of HTML. Here's a basic demo of two different template formats:
{% highlight javascript %} useMustacheTemplates(); //causes templates to use {{}} format
var data = {verb:'jump', subj:'cow', adj:'blue', obj:'moon'};
var ERBView = function() { this.$el = $('
var MustacheView = function() { this.$el = $('
var erbView, mustView; $(function() { erbView = new ERBView(); mustView = new MustacheView(); })
function useMustacheTemplates() { _.templateSettings = { interpolate: /{{(.+?)}}/g }; } {% endhighlight %}