Skip to content

Latest commit

 

History

History
89 lines (74 loc) · 2.5 KB

00-04-05-browser-mocha.md

File metadata and controls

89 lines (74 loc) · 2.5 KB
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:

  1. The module you want to test
  2. The mocha and chai libraries
  3. An empty div with an id of 'mocha' (to hold the test output)
  4. A script which calls mocha.setup('bdd')
  5. Any modules containing your tests
  6. 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 %}

Templates

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 = $('

'); this.template = _.template('The <%=subj%> <%=verb%>s the <%=adj%> <%=obj%>'); this.render = function() { this.$el.html(this.template(data)); // render some data-specific HTML $(document.body).append(this.$el); } }

var MustacheView = function() { this.$el = $('

'); this.template = _.template('The {{ "{{ subj " }}}} {{ "{{ verb " }}}}s the {{ "{{ adj " }}}} {{ "{{ obj " }}}}'); this.render = function() { this.$el.html(this.template(data)); $(document.body).append(this.$el); } })

var erbView, mustView; $(function() { erbView = new ERBView(); mustView = new MustacheView(); })

function useMustacheTemplates() { _.templateSettings = { interpolate: /{{(.+?)}}/g }; } {% endhighlight %}