2013-01-07 37 views
4

我錯過了摩卡咖啡和咖啡/ Javascript這裏顯而易見的東西。我如何測試一個基本的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; 
} 

的功能才能正常工作,但我決定,我需要從今天開始測試這個項目,所以我把在摩卡測試文件:

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)並沒有真正解釋#在那裏做什麼,這僅僅是出於某種原因而出現在這裏的紅寶石成語?

我如何引用ss.coffee文件一定有問題,但我沒有看到它。

回答

9

通過require荷蘭國際集團在節點中的腳本,它會被當作任何其他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 

# ... 

至於...

的文檔(鏈接)真的不解釋什麼#就是在那裏做,[...]

據我所知,一個#通常用來暗示,這是一個方法 - 例如,Constructor#methodName。但是,不確定這是否適用於此。

+3

是的,這是做到了。當你寫這個答案時,在這裏找到答案http://stackoverflow.com/questions/10204021/how-do-i-test-normal-non-node-specific-javascript-functions-with-mocha。我認爲關於#但它看起來很紅寶石,不是嗎?似乎有點不合適。 – jcollum