TypeError: app.address is not a function using chai-http

TypeError: app.address is not a function using chai-http

我正在尝试使用 Fastify 创建一个 micro-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

有人知道我做错了什么吗?

chai.request(app) 不接受 fastify 实例作为记录的输入:

You may use a function (such as an express or connect app) or a node.js http(s) server as the foundation for your request

你应该启动 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 功能 将避免启动服务器侦听,这将大大加快您的测试速度,并且您不会遇到已在使用的端口的问题。

// 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();
      });
    });
  });
});