TypeError: Cannot read property 'address' of undefined supertest

夙愿已清 提交于 2019-12-10 01:24:09

问题


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


来源:https://stackoverflow.com/questions/37044289/typeerror-cannot-read-property-address-of-undefined-supertest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!