如果js不能读取null的属性'should'

我尝试在节点中使用摩卡testing工具。 考虑以下testing场景

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(); }); }); }); }); 

作为testing结果我得到了:

 $ 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 

第一遍没有任何复杂的,但第二个,似乎是,不能附加模块shouldjs。 为什么?

这是一个已知的问题, should库:因为它扩展object ,当然它只有当你有一个具体的对象。 按照定义, null表示你没有对象,你不能调用它的任何方法或者访问它的任何属性。

因此,在这种情况下should是不可用的。

基本上,你有两个select如何处理这个问题:

  1. 你可以交换actualexpected 。 这样,只要你不期望null ,你就有一个对象在开始,因此可以访问它的should属性。 但是,这并不好,因为它改变了语义,并且在所有情况下都不起作用。
  2. 你可以通过另一个没有这个问题的断言库交换should库。

就我个人而言,我会select2,而我个人对此的非常个人的喜爱是节点断言 (这是我写的,因此这是我的最爱)。

无论如何,还有很多其他的select,如预期 。 随意使用这些最适合你的写作风格的断言库。

我有同样的问题。 我解决了它通过使用:

(err === null).should.be.true;

你可以直接使用

 should.not.exist(err); 

还有一个选项我没有在这里提到:

 should(err === null).be.null 

在你的例子中,将会是:

 should(accountExists).be.null