为什么我的mocha/chai错误投掷测试失败?
问题描述:
我有一个简单的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
我知道有数十这里大约答案你传递什么样的期待()是函数不是函数的结果,而且我尝试了每个可以想到的匿名函数的排列,但是我总是得到失败的测试结果。
我认为它必须与我的配置有关,因为我基本上只是运行文档中的示例,或者我对测试中通过或失败的期望未正确校准。
任何线索?
答
这应该可以解决你的问题:
var expect = require('chai').expect;
注意,expect
功能没有被调用。
答
追查它!
向上顶
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
如果你看看调用堆栈,你的测试似乎因为第10行的错误而失败:var err = new ReferenceError('这是一个糟糕的函数');'看起来像你的运行时环境没有'不认识'ReferenceError'。您使用什么浏览器/环境来运行此测试? – 2014-09-27 07:34:52
@AtesGoral:他运行的环境并不重要。你已经发现了这个bug:ReferenceError是未定义的。让它成为答案。 OP要找出为什么没有定义。 – slebetman 2014-09-27 07:43:52
应该是一个香草节点环境,但我会深入探讨缺少ReferenceError。感谢您的洞察 – Khrob 2014-09-27 16:42:08