2014-09-27 38 views
4

我有一個簡單的JavaScript包,我試圖測試。我想檢查錯誤是否被拋出,但是當我的測試運行並且錯誤被拋出時,測試被標記爲失敗。爲什麼我的mocha/chai錯誤投擲測試失敗?

下面的代碼:

var should = require('chai').should(), 
    expect = require('chai').expect(); 

describe('#myTestSuite', function() { 

    it ('should check for TypeErrors', function() { 

     // Pulled straight from the 'throw' section of 
     // http://chaijs.com/api/bdd/ 
     var err = new ReferenceError('This is a bad function.'); 
     var fn = function() { throw err; } 
     expect(fn).to.throw(ReferenceError); 

    }) 

}) 

其中,在運行時給我下面的輸出:

kh:testthing khrob$ npm test 

> [email protected] test /Users/khrob/testthing 
> mocha 



    #myTestSuite 
    1) should check for TypeErrors 


    0 passing (5ms) 1 failing 

    1) #myTestSuite should check for TypeErrors: 
    TypeError: object is not a function 
     at Context.<anonymous> (/Users/khrob/testthing/test/index.js:10:3) 
     at callFn (/Users/khrob/testthing/node_modules/mocha/lib/runnable.js:249:21) 
     at Test.Runnable.run (/Users/khrob/testthing/node_modules/mocha/lib/runnable.js:242:7) 
     at Runner.runTest (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:373:10) 
     at /Users/khrob/testthing/node_modules/mocha/lib/runner.js:451:12 
     at next (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:298:14) 
     at /Users/khrob/testthing/node_modules/mocha/lib/runner.js:308:7 
     at next (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:246:23) 
     at Object._onImmediate (/Users/khrob/testthing/node_modules/mocha/lib/runner.js:275:5) 
     at processImmediate [as _immediateCallback] (timers.js:336:15) 



npm ERR! Test failed. See above for more details. 
npm ERR! not ok code 0 

我知道有數十這裏大約答案你傳遞什麼樣的期待()是函數不是函數的結果,而且我嘗試了每個可以想到的匿名函數的排列,但是我總是得到失敗的測試結果。

我認爲它必須與我的配置有關,因爲我基本上只是運行文檔中的示例,或者我對測試中通過或失敗的期望未正確校準。

任何線索?

+1

如果你看看調用堆棧,你的測試似乎因爲第10行的錯誤而失敗:var err = new ReferenceError('這是一個糟糕的函數');'看起來像你的運行時環境沒有'不認識'ReferenceError'。您使用什麼瀏覽器/環境來運行此測試? – 2014-09-27 07:34:52

+0

@AtesGoral:他運行的環境並不重要。你已經發現了這個bug:ReferenceError是未定義的。讓它成爲答案。 OP要找出爲什麼沒有定義。 – slebetman 2014-09-27 07:43:52

+0

應該是一個香草節點環境,但我會深入探討缺少ReferenceError。感謝您的洞察 – Khrob 2014-09-27 16:42:08

回答

19

這應該可以解決你的問題:

var expect = require('chai').expect; 

注意,expect功能沒有被調用。

1

追查它!

向上頂

expect = require('chai').expect(), 

沒有給我任何有用的東西。它更改爲:

chai = require('chai'), 

然後調用test作爲

chai.expect(fn).to.throw(ReferenceError); 

不正是我的預期。

感謝您的幫助。

+0

接受的答案明顯地解決了你的問題: expect = require('chai')後的括號。期待是問題。 – Konstantin 2017-06-05 17:37:10