如何在 chai 中解析 "Cannot read property 'should' of undefined"?
How to resolve "Cannot read property 'should' of undefined" in 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 = 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
的 old/outdated 版本,因此通常的 should(x).be.a('array')
将不起作用。
或者,您可以直接使用官方 should
包:
$ npm install --save-dev should
并将其用作直接替代品:
const should = require('should');
should(res.body).be.a('array');
我正在尝试测试我的 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
的 old/outdated 版本,因此通常的 should(x).be.a('array')
将不起作用。
或者,您可以直接使用官方 should
包:
$ npm install --save-dev should
并将其用作直接替代品:
const should = require('should');
should(res.body).be.a('array');