为什么我的mocha / chai错误投掷测试失败?

时间:2014-09-27 07:28:21

标签: javascript mocha throw referenceerror chai

我有一个简单的javascript包,我正在尝试测试。我想检查是否抛出了错误,但是当我的测试运行并且抛出错误时,测试被标记为失败。

以下是代码:

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

> testthing@0.1.0 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

我知道这里有几十个答案关于你传递给期望的东西()是一个函数而不是一个函数的结果,我已经尝试了我能想到的匿名函数的每个排列,但我总是得到失败测试结果。

我认为它必须与我的配置有关,因为我基本上只是从文档中运行示例,或者我对测试中的通过或失败的期望没有正确校准。 / p>

任何线索?

2 个答案:

答案 0 :(得分:19)

这可以解决您的问题:

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

请注意,未调用expect函数。

答案 1 :(得分:1)

跟踪它!

在顶部

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

没有给我任何有用的东西。将其更改为:

chai = require('chai'),

然后将测试称为

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

完全符合我的预期。

感谢您的帮助。

相关问题