亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

類型錯誤:app.address 不是使用 chai-http 的函數

類型錯誤:app.address 不是使用 chai-http 的函數

慕哥6287543 2023-10-14 16:03:50
我正在嘗試使用 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有人知道我做錯了什么嗎?
查看完整描述

2 回答

?
慕斯王

TA貢獻1864條經驗 獲得超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避免啟動服務器偵聽的功能,它將大大加快您的測試速度,并且您不會遇到已使用的端口的問題。



查看完整回答
反對 回復 2023-10-14
?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

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

      });

    });

  });

});


查看完整回答
反對 回復 2023-10-14
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號