0

我正在尝试使用 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

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

4

2 回答 2

1

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

您可以使用函数(例如 express 或 connect 应用程序)或 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避免启动服务器侦听的功能,它将大大加快您的测试速度,并且您不会遇到已在使用的端口的问题。

于 2020-12-07T09:02:49.497 回答
0
// 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();
      });
    });
  });
});
于 2021-05-16T01:08:52.107 回答