类型错误:app.address 不是使用 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

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


慕哥6287543
浏览 93回答 2
2回答

慕斯王

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

qq_花开花谢_0

// you must declare the app variable this wayvar 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',()=>{&nbsp; describe('Testing /allstyles',()=>{&nbsp; &nbsp; it('Should return all style names',(done)=>{&nbsp; &nbsp; &nbsp; chai.request(app)&nbsp; &nbsp; &nbsp; .get('/')&nbsp; &nbsp; &nbsp; .end((err,res)=>{&nbsp; &nbsp; &nbsp; &nbsp; expect(res).to.have.status(200);&nbsp; &nbsp; &nbsp; &nbsp; done();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });&nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript