【问题标题】:how do I test a basic javascript file with mocha?如何使用 mocha 测试基本的 javascript 文件?
【发布时间】:2012-12-21 18:05:26
【问题描述】:

我在 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 文件的方式一定有问题,但我没有看到。

【问题讨论】:

    标签: node.js coffeescript mocha.js


    【解决方案1】:

    通过 require 在 Node 中执行脚本,它将被视为任何其他 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
    
    # ...
    

    至于……

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2020-10-28
    • 2013-02-10
    相关资源
    最近更新 更多