rod mclaughlin


Coffeescript testing with Mocha (07 aug 15)

Javascript is one of the most important programming languages in the world. But unlike SQL, or Ruby, it's poorly documented. For some reason, the people who write about Javascript libraries nearly always get it wrong, or miss out a few 'obvious' steps. The language Coffeescript, which generates Javascript, is an exception to the rule - it and its documentation are written by literate people. But it is difficult to find out how to write tests in Coffeescript. All the information is years out of date. I started on this page:

http://code.tutsplus.com/tutorials/better-coffeescript-testing-with-mocha--net-24696

and, after a couple of days of googling, experimenting, and outright guesswork, ended up with this:

  brew install node

  npm install mocha

  npm install chai

  npm install jquery

  npm install -g coffee-script

  npm install node-jsdom

In folder src/, file task.js.coffee:

class Task
  constructor : (@name) ->
root = exports ? window
root.Task = Task

In folder test/, file test.js.coffee:

chai = require 'chai'
chai.should()
expect = chai.expect
CoffeeScript = require('coffee-script')
require('coffee-script/register')
CoffeeScript.register()

Task = require '../src/task.js.coffee'

describe 'Task instance', ->
  task = null
  it 'should have a name', ->
    task = new Task.Task 'feed the cat'
    task.name.should.equal 'feed the cat'

To run the test, cd into the folder above src/ and test/, and enter this:

mocha --compilers coffee:coffee-script/register -R spec



Back
Portland London