Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell Mocha to use CoffeeScript files by default

I'm currently trying to set up testing in Mocha for an application I'm writing using Zappa.js. So far I've been following this tutorial, and converting what I need from JS to Coffeescript.

However I'm a little stuck with trying to run tests. I have a Makefile, which currently looks like this:

REPORTER = dot

test:
  @NODE_ENV=test ./node_modules/.bin/mocha \
    --reporter $(REPORTER) \

.PHONY: test

And I've set up my package.json file to run tests like so:

{
  "scripts": {
    "test": "make test"
  }
}

The issue I'm finding is that, because I'm trying to write my Mocha tests using Coffeescript as well, Mocha does not pick up any of my tests in the "test/" folder when I run "npm test". I know for a fact that I can tell Mocha to run .coffee files by using the following in Terminal (which works):

mocha --compilers coffee:coffee-script

What I want to know is how do I go about telling Mocha to use Coffeescript files by default?

like image 212
Kyri Elia Avatar asked Jun 02 '26 06:06

Kyri Elia


2 Answers

OK I managed to find a way to solve my own question, so I thought I'd share in case anyone else need this.

NOTE: For CoffeeScript 1.7+ --require coffee-script needs to be changed to --require coffee-script/register

The solution is to instead create a Cakefile as opposed to a Makefile, which looks like this:

#Cakefile

{exec} = require "child_process"

REPORTER = "min"

task "test", "run tests", ->
  exec "NODE_ENV=test
    ./node_modules/.bin/mocha
    --compilers coffee:coffee-script
    --reporter #{REPORTER}
    --require coffee-script
    --require test/test_helper.coffee
    --colors
    ", (err, output) ->
      throw err if err
      console.log output

And then change the package.json to this:

#package.json

{
  "scripts": {
    "test": "cake test"
  }
}

Finally I had to install Coffeescript into the project using:

npm install coffee-script

And create a file test/test_helper.coffee, which contains global declarations for the tests.

like image 197
Kyri Elia Avatar answered Jun 04 '26 02:06

Kyri Elia


I configure the mocha tests directly using npm

package.json (scripts only)

"scripts": {
  "start": "node app.js",
  "start-watch": "./node_modules/.bin/node-dev app.js",
  "test": "NODE_ENV=test ./node_modules/.bin/mocha --require coffee-script --compilers coffee:coffee-script --recursive ./test",
  "test-watch": "NODE_ENV=test ./node_modules/.bin/mocha --require coffee-script --compilers coffee:coffee-script --recursive ./test --watch"
}

and then execute the test coffeescript files by running

npm test

or

npm run-script test-watch
like image 24
Stuart McConnell Avatar answered Jun 04 '26 02:06

Stuart McConnell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!