Home » Nodejs » How to use the node.js module 'nodeunit' with coffeescript files

How to use the node.js module 'nodeunit' with coffeescript files

Posted by: admin December 21, 2017 Leave a comment

Questions:

I’m trying to get the nodeunit module working within a coffeescript project but can’t seem to get even a basic test to run.
Here’s my example Coffeescript
require ‘nodeunit’

test = true
test2 = false

exports.testSomething = (test) ->
  test.expect(1)
  test.ok(true, "this should pass")
  test.done()

exports.testSomethingElse = (test2) ->
  test2.expect(1)
  test2.ok(false, "this should fail")
  test2.done()

Unfortunately, when I run ‘$ nodeunit example.coffee’ I get the error output:

example.coffee:4 exports.testSomething = (test) ->
^

module.js:296
throw err;
^ SyntaxError: Unexpected token >
at Module._compile (module.js:397:25)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at require (module.js:346:19)
at /usr/local/lib/node/nodeunit/lib/nodeunit.js:75:37
at /usr/local/lib/node/nodeunit/deps/async.js:508:13
at /usr/local/lib/node/nodeunit/deps/async.js:118:13
at /usr/local/lib/node/nodeunit/deps/async.js:134:9
at /usr/local/lib/node/nodeunit/deps/async.js:507:9

Can anyone help me just get a simplified test up and running in Coffeescript using Node.js?

Thanks in advance

Answers:

Your example runs fine for me. It could be that you’re using an old version of nodeunit, before it had CoffeeScript support; try

npm install -g nodeunit

to update to the latest version.

If that fails, then I suspect that it’s a path issue, so that when nodeunit tries to do require 'coffee-script', it fails.

First do

npm install -g coffee-script

and take note of the last line of the output, which should look something like

coffee-script@1.1.2 /usr/local/lib/node_modules/coffee-script

Now run

echo $NODE_PATH

which in my case is /usr/local/lib/node_modules. You need to set NODE_PATH to the parent directory of the coffee-script directory that npm created, by adding a line like

export NODE_PATH=/usr/local/lib/node_modules

to ~/.profile or ~/.bashrc or whatever else it is your shell runs when it starts, and restart your shell. Then whenever you do require 'coffee-script' from any Node app on your machine, it’ll find the CoffeeScript library.

Questions:
Answers:

If your coffee-script is version 1.7 or later, you may also be suffering from bug #247, for which I just submitted a patch.