【问题标题】:"TypeError: app.address is not a function" despite exporting the server“TypeError:app.address 不是函数”尽管导出了服务器
【发布时间】:2020-12-27 10:26:58
【问题描述】:

我已经构建了我的 API 的初始配置,并正在尝试使用 Jest 和 Supertest 来设置测试。

尽管通过 Stack Overflow 和 supertest 文档进行了大量搜索,但我仍然无法解决此错误:

TypeError: app.address 不是函数

我意识到我需要将我的服务器导出到 Jest 测试脚本中,并认为这是我通过将我的 app.listen 设置为服务器并导出它来设法做到的,因为这是在相关解决方案中找到的,但它没有在这里工作。

index.js

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const cors = require('cors');
const pool = require('./db');
const verifyToken = require('./helpers/verifyToken');
const { ppid } = require('process');
const PORT = process.env.PORT || 5000;
//process.env.PORT

// Middleware
app.use(cors());
app.use(express.json());

// API ROUTES
var user = require('./routes/user');
var contact = require('./routes/contact');
var organization = require('./routes/organization');
var group = require('./routes/group');
app.use('/user', user);
app.use('/contact', contact);
app.use('/organization', organization);
app.use('/group', group);

// PAGE ROUTES
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname + '/public/index.html'));
});

app.get('/home', (req, res) => {
  res.sendFile(path.join(__dirname + '/public/home.html'));
});

app.get('*', (req, res) => {
  res.status(400).send({ error: 'Incorrect Endpoint' });
});

// EXPRESS START
const server = app.listen(PORT, () => {
  console.log(`Server has started on port ${PORT}`);
});

module.exports = { server };

user.js

// All User Related Routes
const express = require('express');
const pool = require('../db');
const verifyToken = require('../helpers/verifyToken');
const generateToken = require('../helpers/generateToken');
const jwt = require('jsonwebtoken');
const router = express.Router();

// Get All Users or User By ID
router.get('/:id?', verifyToken, async (req, res) => {
  const { id } = req.query;
  try {
    if (id) {
      const { id } = req.query;
      const getUser = await pool.query('SELECT * FROM users WHERE id = $1', [
        id,
      ]);
      res.json(getUser.rows);
    } else {
      const getUser = await pool.query('SELECT * FROM users');
      res.json(getUser.rows);
    }
  } catch (err) {
    console.log(err.message);
  }
});
module.exports = router;

first_test.js

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

describe('GET /user', function () {
  it('responds with json', function (done) {
    request(app)
      .get('/user')
      .auth('username', 'password')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

error.js

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "Server has started on port 5000".


      at CustomConsole.log (../../../../usr/local/lib/node_modules/jest/node_modules/@jest/console/build/CustomConsole.js:186:10)
      at Server.<anonymous> (index.js:55:11)

 FAIL  __tests__/first.test.js
  GET /user
    ✕ responds with json (2 ms)

  ● GET /user › responds with json

    TypeError: app.address is not a function

       5 |   it('responds with json', function (done) {
       6 |     request(app)
    >  7 |       .get('/user')
         |        ^
       8 |       .auth('username', 'password')
       9 |       .set('Accept', 'application/json')
      10 |       .expect('Content-Type', /json/)

      at Test.serverAddress (node_modules/supertest/lib/test.js:55:18)
      at new Test (node_modules/supertest/lib/test.js:36:12)
      at Object.get (node_modules/supertest/index.js:25:14)
      at Object.<anonymous> (__tests__/first.test.js:7:8)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.486 s
Ran all test suites.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

【问题讨论】:

    标签: javascript node.js express jestjs supertest


    【解决方案1】:

    当您使用 supertest 进行测试时,它会创建自己的虚拟连接。所以它只需要一个 app 实例,而不是一个 server 实例(服务器是侦听端口的应用程序)。所以你需要做的就是将你的服务器分离到另一个文件中,server.js:

    server.js 的内容将是:

    const app = require('./index.js');
    const PORT = process.env.PORT || 5000;
    const server = app.listen(PORT, () => {
        console.log(`Server has started on port ${PORT}`);
    });
    
    module.exports = { server };
    

    而内容 index.js 将是:

    ...
    ...
    ...
    app.get('*', (req, res) => {
      res.status(400).send({ error: 'Incorrect Endpoint' });
    });
    
    module.exports = app;
    

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2016-03-03
      • 1970-01-01
      • 2013-03-28
      • 2018-12-04
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      相关资源
      最近更新 更多