Node.js 如何解决;无法读取属性';应该';“未定义”的定义;在柴?
我试图测试我的RESTful nodejs API,但一直遇到以下错误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
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()