我尝试在节点中使用测试工具mocha。考虑以下测试场景
var requirejs = require('requirejs');
requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});
describe('Testing controller', function () {
it('Should be pass', function (done) {
(4).should.equal(4);
done();
});
it('Should avoid name king', function (done) {
requirejs(['../server/libs/validate_name'], function (validateName) {
var err_test, accountExists_test, notAllow_test, available_test;
validateName('anu', function (err, accountExists, notAllow, available) {
accountExists.should.not.be.true;
done();
});
});
});
});
作为测试结果,我得到了:
$ make test
./node_modules/.bin/mocha \
--reporter list
. Testing controller Should be pass: 0ms
1) Testing controller Should avoid name anu
1 passing (560 ms)
1 failing
1) Testing controller Should avoid name anu:
Uncaught TypeError: Cannot read property 'should' of null
at d:\townspeech\test\test.spec.js:23:30
at d:\townspeech\server\libs\validate_name.js:31:20
at d:\townspeech\test\test.spec.js:22:13
at Object.context.execCb (d:\townspeech\node_modules\requirejs\bin\r.js:1869:33)
at Object.Module.check (d:\townspeech\node_modules\requirejs\bin\r.js:1105:51)
at Object.Module.enable (d:\townspeech\node_modules\requirejs\bin\r.js:1376:22)
at Object.Module.init (d:\townspeech\node_modules\requirejs\bin\r.js:1013:26)
at null._onTimeout (d:\townspeech\node_modules\requirejs\bin\r.js:1646:36)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
make: *** [test] Error 1
第一次通过没有任何复杂,但第二次,似乎,不能附加模块应该it。为什么?
发布于 2013-08-07 04:06:13
这是should
库中已知的一个问题:在扩展object
时,当然只有当您有一个具体的对象时,它才能工作。根据定义,null
意味着您没有对象,因此不能调用它上的任何方法或访问它的任何属性。
因此,在这种情况下should
是不可用的。
基本上,对于如何处理这个问题,您有两个选择:
actual
和expected
。这样,只要您不期望null
,您在开始时就有一个对象,因此可以访问它的should
属性。但是,这并不好,因为它改变了语义,而且并不是在所有情况下都有效。should
库。就我个人而言,我会选择选项2,而我个人最喜欢的选项是node-assertthat (它是由我编写的,因此它是我的最爱)。
无论如何,还有很多其他选项,比如expect。可以随意使用这些最适合您的测试风格的断言库。
发布于 2013-11-14 22:29:12
我也有同样的问题。我用以下方法解决了这个问题:
(err === null).should.be.true;
发布于 2014-03-12 10:23:31
你可以直接使用应该
should.not.exist(err);
https://stackoverflow.com/questions/18102152
复制相似问题