node.js - 如何使用 mocha 测试基本的 javascript 文件?

标签 node.js coffeescript mocha.js

我在 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;
}

函数运行正常,但我决定今天开始测试这个项目,所以我放入了一个 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")

有些地方不对,因为我的结果是:

 $  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      

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

我尝试将 sortRowCol(a,b) 更改为 #sortRowCol(a, b) ,反之亦然,但没有帮助。文档 ( link ) 并没有真正解释 # 在那里做什么,这只是出于某种原因在这里的 ruby 成语吗?

我引用 ss.coffee 文件的方式肯定有问题,但我没有看到它。

最佳答案

通过 requireNode 中的脚本,它将被视为任何其他 module , 将 sortRowCol 隔离为闭包中的局部变量。该脚本将必须使用 exportsmodule.exports 使其可用于 mocha:

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

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

# ...

至于...

The docs (link) don't really explain what that # is doing there, [...]

据我所知,# 通常用于暗示它是一种方法——例如,Constructor#methodName。不过,不确定这是否适用于此。

关于node.js - 如何使用 mocha 测试基本的 javascript 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14205631/

相关文章:

javascript - Mocha : get stacktrace when running mocha programmatically

node.js - 如果不存在则创建 S3 存储桶

node.js - nodejs+express文件上传tmp名称唯一

javascript - 在 CoffeeScript/JavaScript 中导入命名空间

python - 没有 node.js 的 CoffeeScript 编译器?

javascript - Puppeteer 失败时自定义错误消息

node.js - 如何消费braintree返回的 Node 流

javascript - nodejs 不读取 JSON

javascript - 记录每个方法?

node.js - 在 Mocha 测试期间静音 stdout 和 stderr