微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有 TypeError 的 Jest/Supertest 错误:app.address is not a function

如何解决带有 TypeError 的 Jest/Supertest 错误:app.address is not a function

首先,我尝试了答案 here - 没有帮助解决,接受的答案没有解决我的问题。

我正在尝试使用 Jest/Supertest 测试我的 API 端点。从一个简单的 /test 端点开始。但是,当我运行测试时,我得到: TypeError: app.address is not a function

app.js

...
// Set server (default to 3000)
  app.set('port',process.env.PORT || 3000);
  // Start server
  const server = http.listen(app.get('port'),() => {
    logger.info(`Worker ${process.pid} running on ${app.get('port')} in ${app.get('env')} mode`);
  });

  module.exports = server;
...

app.test.js

const server = require('./app');
const supertest = require('supertest');
const request = supertest(server);

it('Gets the test endpoint',async (done) => {
  // Sends GET Request to /test endpoint
  const res = await request.get('/test');
  done();
});

测试运行输出

FAIL  ./app.test.js
  ✕ Gets the test endpoint (24 ms)

  ● Gets the test endpoint

    TypeError: app.address is not a function

      14 | it('Gets the test endpoint',async (done) => {
      15 |   // Sends GET Request to /test endpoint
    > 16 |   const res = await request.get('/test');
         |                             ^
      17 |
      18 |   // ...
      19 |   done();

欢迎提供任何意见,谢谢。

解决方法

来自上面 @jonrsharpe 的评论是正确答案:

Supertest 使用的是应用程序,而不是服务器。您不需要监听,它会为您设置端口(这是好处之一 - stackoverflow.com/a/62992056/3001761)。我建议将应用程序和服务器部分分开,就像我在这里所做的那样https://github.com/textbook/starter-kit/tree/1567d269b8afe5d93408202900ac0ac1473fd89e/server

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。