如何使用mocha测试基本的javascript文件?

jco*_*lum 5 mocha.js node.js coffeescript

我在Mocha和Coffeescript/Javascript中遗漏了一些明显的东西.

我有一个/static/js/调用的文件ss.coffee,它很简单,只有一个函数:

function sortRowCol(a, b) {
    if (a.r == b.r)
        if (a.c == b.c)
            return 0;
        else if (a.c > b.c)
            return 1;
        else return -1;
    else if (a.r > b.r)
        return 1;
    else return -1;
}
Run Code Online (Sandbox Code Playgroud)

该功能正常,但我决定今天需要开始测试这个项目,所以我输入了一个mocha测试文件:

require "../static/js/ss.coffee"

chai = require 'chai'
chai.should()

describe 'SS', ->
    describe '#sortRowCol(a,b)', ->
      it 'should have a sorting function', ->
        f = sortRowCol
        debugger
        console.log 'checking sort row'
        f.should.not.equal(null, "didn't find the sortRowCol function")
    describe 'sortRowCol(a, b)', ->
      it 'should return -1 when first row is less than second', ->
        a = {r: 2, c: "A"}
        b = {r: 1, c: "A"}
        r = sortRowCol a, b
        r.should.equal(-1, "didn't get the correct value")
Run Code Online (Sandbox Code Playgroud)

有些事情是不对的,因为我的结果是:

 $  mocha --compilers coffee:coffee-script ./test/ss.coffee -R spec           
 SS                                                                      
   #sortRowCol(a,b)                                                              
     1) should have a sorting function                                           
   sortRowCol(a, b)                                                              
     2) should return -1 when first row is less than second                      


 × 2 of 2 tests failed:                                                          

 1) SS #sortRowCol(a,b) should have a sorting function:                 
    ReferenceError: sortRowCol is not defined      
Run Code Online (Sandbox Code Playgroud)

它正确找到文件,因为如果我将其更改为不存在的文件名,它将会出现"无法找到模块"的错误.

我尝试改变sortRowCol(a,b),#sortRowCol(a, b)反之亦然,没有帮助.文档(链接)并没有真正解释#在那里做了什么,这只是因为某种原因出现在这里的红宝石成语吗?

我如何引用ss.coffee文件肯定有问题,但我没有看到它.

Jon*_*ski 11

通过require在Node中编写脚本,它将被视为任何其他模块,sortRowCol在闭包中隔离为本地.该脚本必须使用exportsmodule.exports使其可用于mocha:

function sortRowCol(a, b) {
    // ...
}

if (typeof module !== 'undefined' && module.exports != null) {
    exports.sortRowCol = sortRowCol;
}
Run Code Online (Sandbox Code Playgroud)
ss = require "../static/js/ss.coffee"
sortRowCol = ss.sortRowCol

# ...
Run Code Online (Sandbox Code Playgroud)

至于...

文档(链接)并没有真正解释#在那里做什么,[...]

AFAIK,a #通常用于暗示它是一种方法 - 例如,Constructor#methodName.但是,不确定这是否适用于此.

  • 是的,做到了.在您撰写此答案时,请在此处找到答案http://stackoverflow.com/questions/10204021/how-do-i-test-normal-non-node-specific-javascript-functions-with-mocha.我假设关于#但它似乎非常Ruby-ish,不是吗?似乎有点不合适. (3认同)