我正在尝试用Fastify创建一个微api,现在我正在测试这个应用程序,但是我得到了这个错误:
Testing /allstyles
Should return all style names:
TypeError: app.address is not a function
at serverAddress (node_modules/chai-http/lib/request.js:282:18)
at new Test (node_modules/chai-http/lib/request.js:271:53)
at Object.obj.<computed> [as get] (node_modules/chai-http/lib/request.js:239:14)
at Context.<anonymous> (test/routes-chai.js:12:8)
at processImmediate (internal/timers.js:461:21)我的应用程序文件是这样的:
const fastify = require('fastify');
var app = fastify({
logger:{level:'error',prettyPrint:true}
});
app.get('/',(req,res)=>{
console.log('Hello world');
res.code(200);
});
module.exports = app;我的测试文件是:
var expect = require('chai').expect;
var app = require('../app/main.js');
var chaiHttp = require('chai-http');
var chai = require('chai');
chai.use(chaiHttp);
describe('Testing routes',()=>{
describe('Testing /allstyles',()=>{
it('Should return all style names',(done)=>{
chai.request(app)
.get('/')
.end((err,res)=>{
expect(res).to.have.status(200);
done();
});
});
});
});我试过:
module.exports = app.listen(3000);和
module.exports = {app}但它总是会给我一些错误,比如这个或那个错误,上面写着:
TypeError: Cannot read property 'address' of undefined有人知道我做错了什么吗?
发布于 2020-12-07 09:02:49
chai.request(app)不接受fastify实例作为输入,如文档所示:
您可以使用函数(例如快递或连接应用程序)或node.js http(s)服务器作为请求的基础。
您应该启动fastify服务器并将其交给chai:
var expect = require('chai').expect;
var app = require('./index.js');
var chaiHttp = require('chai-http');
var chai = require('chai');
chai.use(chaiHttp);
app.listen(8080)
.then(server => {
chai.request(server)
.get('/')
.end((err, res) => {
expect(res).to.have.status(200);
app.close()
});
})这将如预期的那样工作。
注意:您的HTTP处理程序不调用reply.send,因此请求将超时,您也需要修复它:
app.get('/', (req, res) => {
console.log('Hello world');
res.code(200);
res.send('done')
});另外,我建议尝试fastify.inject特性,这样可以避免启动服务器侦听,这样会大大加快您的测试速度,并且您将不会遇到已经在使用的端口的问题。
发布于 2021-05-16 01:08:52
// you must declare the app variable this way
var expect = require('chai').expect;
var app = require('../app/main.js').app;
var chaiHttp = require('chai-http');
var chai = require('chai');
chai.use(chaiHttp);
describe('Testing routes',()=>{
describe('Testing /allstyles',()=>{
it('Should return all style names',(done)=>{
chai.request(app)
.get('/')
.end((err,res)=>{
expect(res).to.have.status(200);
done();
});
});
});
});https://stackoverflow.com/questions/65152625
复制相似问题