无法使用CoffeeScript运行Mocha

时间:2012-03-30 10:03:07

标签: coffeescript mocha

Makefile - 内容:

REPORTER = dot

all: build

build:
    @./node_modules/coffee-script/bin/coffee \
        -c \
        -o lib src

clean:
    rm -rf lib
    mkdir lib

watch:
    @./node_modules/coffee-script/bin/coffee \
        -o lib \
        -cw src

test:
    @./node_modules/mocha/bin/mocha \
        --reporter $(REPORTER) \
        test/*.coffee

.PHONY: build clean watch test

项目根目录有一个包含两个文件的测试文件夹:mocha.opts和example.coffee

example.coffee - 内容

describe "feature", ->
   it "should add two numbers", ->
       (2+2).should.equal 4

在运行make test时,收到以下错误:

cribe 'feature',
      ^^^^^^^^^

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
SyntaxError: Unexpected string
    at Module._compile (module.js:429:25)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at /home/my_username/testcode/coffeepress/node_modules/mocha/bin/_mocha:261:27
    at Array.forEach (native)
    at load (/home/my_username/testcode/coffeepress/node_modules/mocha/bin/_mocha:258:9)
    at Object.<anonymous> (/home/my_username/testcode/coffeepress/node_modules/mocha/bin/_mocha:249:1)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

使用js文件运行Mocha成功,但无法使用CoffeeScript运行它。我真的很想 - 为了代码简洁。

请指导。

6 个答案:

答案 0 :(得分:90)

从摩卡1.0开始:

  

咖啡脚本不再支持开箱即用。可以通过映射文件扩展名(与--watch一起使用)和模块名称来使用CS和类似的转换器。例如,使用CoffeeScript 1.6的--compilers coffee:coffee-script或使用CoffeeScript 1.7 +的--compilers coffee:coffee-script/register

(引用http://visionmedia.github.io/mocha/#compilers-option)因此,您需要添加一行

--compilers coffee:coffee-script/register

或,对于CS&lt; = 1.6.x,

--compilers coffee:coffee-script

到您的mocha.opts文件。

答案 1 :(得分:29)

从CoffeeScript 1.7开始,选项应为:

--compilers coffee:coffee-script/register

在Mocha的github网站上提交了issue

答案 2 :(得分:1)

显然,摩卡在2018年4月的变化(轻柔地)弃用了--compilers选项。在命令行中,您现在得到:

  

(node:27864)弃用警告:“ - 编译器”将在未来版本的Mocha中删除;有关详细信息,请参阅https://git.io/vdcSr

与链接一样,只需不使用--compilers并使用此新的(简化的)mocha.opts选项即可轻松解决此问题:

--require coffeescript/register

test/*.coffee

需要最后一行才能让Mocha了解它现在应该使用*.coffee个文件作为测试文件。 --require选项似乎没有涵盖这一点。

答案 3 :(得分:1)

使用最新的摩卡(mocha),require语句必须以package.json文件的形式编写

  "mocha":{
    "require":"coffeescript",
    "reporter":"spec"
  },

答案 4 :(得分:0)

我需要对我的mocha args进行两项更改才能使其正常工作:

--require coffee-script/register
--compilers coffee:coffee-script/register

答案 5 :(得分:0)

mocha --require coffeescript/register

来源:https://github.com/mochajs/mocha/wiki/compilers-deprecation