TypeError:无法读取未定义的supertest的属性"address"

Sai*_*ama 12 mocha.js node.js supertest

我需要一些帮助来解决我在nodejs代码上测试的问题.我正在使用摩卡和超级.我对supertest中的实现感到困惑.我不知道解决了.我正在尝试自动下载文件.

`describe('GET /entry/:entryId/file/:id/download', function(){
 it('should pass download function', function(done){
   this.timeout(15000);
   request(app.webServer)
  .get('/entry/543CGsdadtrE/file/wDRDasdDASAS/download')
  .set('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGco')
  .expect(200)
  .end(function(err, res){
  if (err) return done(err);
  console.log(err, res);
  done();
 });
});
});
Run Code Online (Sandbox Code Playgroud)

Col*_*n D 16

在测试快速应用时,我收到了来自摩卡的类似错误.错误全文:

0 passing (185ms)
2 failing

1) loading express responds to /:
 TypeError: app.address is not a function
  at Test.serverAddress (test.js:55:18)
  at new Test (test.js:36:12)
  at Object.obj.(anonymous function) [as get] (index.js:25:14)
  at Context.testSlash (test.js:12:14)

2) loading express 404 everything else:
 TypeError: app.address is not a function
  at Test.serverAddress (test.js:55:18)
  at new Test (test.js:36:12)
  at Object.obj.(anonymous function) [as get] (index.js:25:14)
  at Context.testPath (test.js:17:14)
Run Code Online (Sandbox Code Playgroud)

我通过将它添加到我的express server.js来修复它,即导出服务器对象

module.exports = app
Run Code Online (Sandbox Code Playgroud)

  • 无论 `module.exports = app` 还是 `module.exports = {app}` 解决问题都与测试套件如何使用它有关,例如 `const {app} = require("./your-server") ` 或 `const app = require("./your-server")`。无论您如何导出/导入它,重要的是“chai.request(app)”实际上被赋予了一个真正的应用程序对象,而不是像未定义或其他对象之类的东西。 (2认同)

Art*_*tru 6

面对此错误的Typescript用户检查两件事:

  1. 快递服务器应该有module.exports = app(感谢@Collin D)
  2. 使用import * as app from "./app"
    而不是错误 import app from "./app"