TypeError: Cannot read property 'address' of undefined supertest

橙三吉。 提交于 2019-12-05 01:05:55

I received a similar error from mocha when testing an express app. Full text of error:

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)

I fixed it by adding this to my express server.js, i.e. export the server object

module.exports = app

Typescript users, who are facing this error, check two things:

  1. The express server should have module.exports = app (thanks to @Collin D)
  2. Use import * as app from "./app"
    instead of wrong import app from "./app"

I was facing same problem, above solution didn't work for me, some one in my shoes kindly follow this guy's

exports in server.js should be

module.exports.app = app;

If you have multiple modules than use es6 feature

module.exports = {
  app,
  something-else,
  and-so-on
}

my package.json for version cross ref..

{
  "name": "expressjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha **/*.test.js",
    "start": "node app.js",
    "test-watch": "nodemon --exec npm test"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "hbs": "^4.0.1"
  },
  "devDependencies": {
    "mocha": "^5.2.0",
    "supertest": "^3.3.0"
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!