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

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

如何解决尽管导出了服务器,但“ 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;

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