node.js - Jest/ super 测试错误,类型错误 : app. 地址不是函数

标签 node.js express jestjs supertest

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

我正在尝试使用 Jest/Supertest 测试我的 API 端点。从简单的/test 端点开始。但是,当我运行测试时,我得到: 类型错误:app.address 不是函数

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 takes the app, not the server. You don't need to listen, it sets up the port for you (that's one of the benefits - stackoverflow.com/a/62992056/3001761). I'd recommend splitting up the app and the server parts, as I've done here https://github.com/textbook/starter-kit/tree/1567d269b8afe5d93408202900ac0ac1473fd89e/server

关于node.js - Jest/ super 测试错误,类型错误 : app. 地址不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65719047/

相关文章:

node.js - (libuv)kqueue(): Too many open files in system when trying to write a file in Node Js

node.js - 夜巡在 browser.end() 之后不会终止

javascript - 表达静态和setHeaders : "Error: Can' t set headers after they are sent.“

jestjs - Nrwl/Nx jest.preset.js - 如何在配置中使用 projectName 值

javascript - TypeError : sentimentCurrent. map 不是一个函数?

javascript - 使用转义正则表达式特殊字符进行测试时字符串相等性失败

javascript - Promise.allSettled 在 babel ES6 实现中

javascript - 将观察者存储在全局变量中,稍后使用

javascript - Node/JS - 类构造函数变量未定义

javascript - 错误 : Can't set headers after they are sent to the client