Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何解决;无法读取属性';应该';“未定义”的定义;在柴?_Node.js_Mocha.js_Chai - Fatal编程技术网

Node.js 如何解决;无法读取属性';应该';“未定义”的定义;在柴?

Node.js 如何解决;无法读取属性';应该';“未定义”的定义;在柴?,node.js,mocha.js,chai,Node.js,Mocha.js,Chai,我试图测试我的RESTful nodejs API,但一直遇到以下错误 Uncaught TypeError: Cannot read property 'should' of undefined 我正在为我的API使用restify框架 'use strict'; const mongoose = require('mongoose'); const Customer = require('../src/models/customerSchema'); const chai = requ

我试图测试我的RESTful nodejs API,但一直遇到以下错误

Uncaught TypeError: Cannot read property 'should' of undefined
我正在为我的API使用restify框架

'use strict';

const mongoose = require('mongoose');
const Customer = require('../src/models/customerSchema');

const chai = require('chai');
const chaiHttp = require('chai-http');
const server = require('../src/app');
const should = chai.should();

chai.use(chaiHttp);

describe('Customers', () => {
   describe('/getCustomers', () => {
       it('it should GET all the customers', (done) => {
           chai.request(server)
               .get('/getCustomers')
               .end((err, res) => {
                   res.should.have.status(200);
                   res.body.should.be.a('array');
                   done();
                });
       });
   });
});
当我删除行
res.body.should.be.a('array')时,测试工作正常

是否有任何方法可以解决此问题

通常,当您怀疑某个值可能是
undefined
null
时,您会在调用
should()
时包装该值,例如
should(res.body)
,因为引用
null
undefined
上的任何属性都会导致异常

但是,Chai使用了一个旧版本的
should
,它不支持此操作,因此您需要事先声明该值的存在

相反,请再添加一个断言:

should.exist(res.body);
res.body.should.be.a('array');
Chai使用了一个旧/过时版本的
should
,因此通常的
should(x).be.a('array')
不起作用


或者,您可以直接使用官方软件包:

$ npm install --save-dev should
并将其作为替换品:

const should = require('should');

should(res.body).be.a('array');

现在我得到了错误
uncaughttypeerror:should不是一个函数
常数应=chai.should。我按照您所说的更改了行,但是现在我得到了
未捕获的TypeError:无法读取未定义的属性“have”
。我的代码是
res.should.have.status(200);should(res.body).be.a('array')
@BattleFrog Chai使用精简版的
should
。查看我的最新答案(忽略我的最后一条评论-保留括号,您确实需要它们)。
chai.should().exist(…)
.should.work()