TypeError: Cannot read property 'address'

2019-04-20 23:04发布

问题:

I need some help to resolve my problem with testing on nodejs codes. I'm using mocha and supertest. I'm confused with the implementation in supertest. I don't know to resolved it. I'm trying to automate downloading a file.

`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();
 });
});
});

回答1:

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


回答2:

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"


回答3:

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"
  }
}