尽管导出了服务器,但“ TypeError:app.address不是函数” index.js user.js first_test.js error.js

问题描述

我已经建立了API的初始配置,并尝试使用Jest和Supertest进行测试。

尽管通过Stack Overflow和超级测试文档进行了广泛搜索,但我仍无法解决错误

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',res) => {
  res.sendFile(path.join(__dirname + '/public/home.html'));
});

app.get('*',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.

解决方法

使用超级测试进行测试时,它将创建自己的虚拟连接。因此,它只需要一个 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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...