应该js无法读取属性'should'为null

zer*_*ing 31 node.js should.js

我尝试在节点中使用测试工具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();
            });

        });
    });

});  
Run Code Online (Sandbox Code Playgroud)

作为测试结果我有:

$ 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
Run Code Online (Sandbox Code Playgroud)

第一次传递没有任何复杂,但第二次,似乎,无法附加模块shouldjs.为什么?

Hen*_*Tao 77

我有同样的问题.我用以下方法解决了它:

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


小智 29

你可以直接使用

should.not.exist(err);
Run Code Online (Sandbox Code Playgroud)

  • `should.not.exist(err);`未捕获TypeError:对象#<断言>没有方法'存在' (7认同)

Gol*_*den 9

这是should库的一个已知问题:当它扩展时object,它当然只有在你有一个具体对象时才有效.因为null,根据定义,意味着您没有对象,您不能在其上调用任何方法或访问其任何属性.

因此,should在这种情况下不可用.

基本上,您有两种方法可以解决这个问题:

  1. 你可以交换actualexpected.这样,只要你没有想到null,你在开头有一个对象,因此可以访问它的should属性.但是,这并不好,因为它改变了语义,并不适用于所有情况.
  2. 您可以should通过另一个没有此问题的断言库来交换库.

就个人而言,我选择2,我个人最喜欢的是节点断言(这是我写的,因此它是我最喜欢的).

无论如何,还有很多其他选择,比如期待.随意使用最适合您编写测试风格的任何这些断言库.

  • 您可以使用shuold使用should.exists(object)测试空对象 (22认同)
  • +1 @Mbrevda,它实际上是`should.exist` (5认同)
  • 好的电话,@ zaboco.```should.exist(object)```是正确的调用方法.我实际上无法编辑我的评论思想:( (2认同)

Mbr*_*vda 5

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

should(err === null).be.null
Run Code Online (Sandbox Code Playgroud)

在你的例子中,那将是:

should(accountExists).be.null
Run Code Online (Sandbox Code Playgroud)