ChaiJS不处理exception
这是一个NodeJS模块:
var plural = function(words, num) { if (words.length != 3) { throw new Error('Wrong words array'); } var lastNum = num % 10; var second = (num / 10) % 10; if (second == 1) return words[2] else if (lastNum == 1) return words[0]; else if (lastNum <= 4) return words[1]; else return words[2]; }; module.exports = plural;
这里是模块testing:
var expect = require('chai').expect; var plural = require('../plural') describe('Test with wrong array', function() { it('Must throw Error', function() { expect(plural(['я','меня'])).to.throw(Error); }); });
我想testingexception抛出。 但这是mocha
:
Test with wrong array 1) Must throw Error 1 failing 1) Test with wrong array Must throw Error: Error: Wrong words array at plural (C:\Users\home\Google Drive\Учеба\Спецкурсы\Яндекс.Интерфейсы\TestableCode\testable-code-01\plural.js:3:9) at Context.<anonymous> (C:\Users\home\Google Drive\Учеба\Спецкурсы\Яндекс.Интерфейсы\TestableCode\testable-code-01\test\cat.test.js:31:10) at callFn (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:250:21) at Test.Runnable.run (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:243:7) at Runner.runTest (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:373:10) at C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:451:12 at next (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:298:14) at C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:308:7 at next (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:246:23) at Object._onImmediate (C:\Users\home\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:275:5) at processImmediate [as _immediateCallback] (timers.js:345:15)
所以,我的代码抛出exception,这是正确的行为,并应通过testing。 但是不是。 有什么问题?
Chai的to.throw()方法是一个assertThrows方法的简写,它需要将一些parameter passing给它。 你可以在这里看到一个to.throw()的例子。 它看起来像throws()需要通过你将抛出的错误的构造函数。
如果您对抛出自定义错误信息感兴趣,可以在Chai的独立库“assertion-error”中看到AssertionError的定义。
在你的情况,你应该能够通过Error.constructor
或Error
我会想象达到相同的效果。
expect(plural(['я','меня'])).to.throw(Error);
另外,你必须通过引用来传递期望的函数 – 在函数被用作期望的参数之前,你正在执行这个函数:
expect(function(){ plural(['я','меня']); }).to.throw(Error);
也许这条线:
expect(plural(['я','меня'])).to.throw();
应该读
expect(plural(['я','меня'])).to.throw(Error);
如果我只是取代你的expect(plural...
线)
expect(plural.bind(undefined, ['я','меня'])).to.throw(Error);
那么它的工作。
正如netpoetica所解释的那样,你不能只是把plural(...)
放在expect
内部,因为plural
是在 expect
执行之前被调用的,而expect
得到的却是plural
的返回值 ,但是因为它抛出一个exception, expect
不会执行。 此外, expect
是一个函数, 它会调用来检查是否引发exception。 netpoetica使用匿名function来做到这一点。 我更喜欢使用bind
。 在上面的代码中做了什么bind
是从plural
创build一个新的函数,当被调用将有this
设置的值为undefined
和第一个参数设置为['я','меня']
。