未捕获的错误:监听EADDRINUSE:摩卡单元测试时,地址已经在使用::: 3000

时间:2019-05-25 20:48:03

标签: node.js express mocha

单元测试代码时出现此错误,

  

2次通过(14ms)1次失败

     

1)测试套件外部未捕获的错误:        未捕获的错误:侦听EADDRINUSE:地址已在使用::: 3000         在Server.setupListenHandle上[作为_listen2](net.js:1255:14)         在listenInCluster(net.js:1303:12)         在Server.listen(net.js:1391:7)         在Function.listen(node_modules / express / lib / application.js:618:24)         在Object.listen(main.js:39:5)         在Module._compile(内部/模块/cjs/loader.js:721:30)         在Module._compile(node_modules / pirates / lib / index.js:99:24)         在Module._extensions..js(内部/模块/cjs/loader.js:732:10)         at Object.newLoader [as .js](node_modules / pirates / lib / index.js:104:7)         在Module.load(internal / modules / cjs / loader.js:620:32)         在tryModuleLoad(内部/模块/cjs/loader.js:560:12)         在Function.Module._load(internal / modules / cjs / loader.js:552:3)         在Module.require(内部/模块/cjs/loader.js:657:17)         在要求时(内部/模块/cjs/helpers.js:22:18)         在对象。 (测试/ main.test.js:4:1)         在Module._compile(内部/模块/cjs/loader.js:721:30)         在Module._compile(node_modules / pirates / lib / index.js:99:24)         在Module._extensions..js(内部/模块/cjs/loader.js:732:10)         at Object.newLoader [as .js](node_modules / pirates / lib / index.js:104:7)         在Module.load(internal / modules / cjs / loader.js:620:32)         在tryModuleLoad(内部/模块/cjs/loader.js:560:12)         在Function.Module._load(internal / modules / cjs / loader.js:552:3)         在Module.require(内部/模块/cjs/loader.js:657:17)         在要求时(内部/模块/cjs/helpers.js:22:18)         在Array.forEach()         在StatWatcher.onchange(internal / fs / watchers.js:50:8)

我正在使用mocha,并且我的package.json上有--watch。我正在使用es6方法来表达。

Package.json

{
  "name": "elies6express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/.bin/mocha --watch --require @babel/register",
    "start": "nodemon --exec babel-node main.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "bookshelf": "^0.14.2",
    "chai-http": "^4.3.0",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.0",
    "knex": "^0.16.5",
    "morgan": "^1.9.1",
    "path": "^0.12.7",
    "pg": "^7.11.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/node": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/register": "^7.4.4",
    "chai": "^4.2.0",
    "mocha": "^6.1.4",
    "nodemon": "^1.19.0",
    "reify": "^0.19.1",
    "request": "^2.88.0"
  }
}

main.js

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';

const app = express();

app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.use('/users', userRoute);

app.use(() => (req, res, next)  =>{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
app.use(bodyParser.urlencoded({ extended:false})); 

//build mode
// app.get('*', (req, res) => {
//   res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })

app.listen(process.env.PORT, () =>
  console.log(`Example app listening on port ${process.env.PORT}!`),
);

export default app;

main.test.js

import chai from "chai"
import chaiHttp from 'chai-http';
import request from 'request';
import server from '../main';
const expect = chai.expect;
const should = chai.should();


chai.use(chaiHttp);

// should get / 

describe('should GET /',  () => {
    it('should get 200 status', (done) =>{
        chai.request(server)
        .get('/')
        .end( (err, res) => {
            res.should.have.status(200);
            done();
        });
    });

})
// should check for Hello World!
describe('Should check for Hello World! text', () => {
    it('should check for hello world text', (done) =>{
        chai.request(server)
        .get('/')
        .end( (err, res) => {
            expect(res.body).to.be.an('object') // works
            expect(res.text).to.equal('Hello World!')  // use res.text to check for res.send() text
            done();
        })
    })

})

5 个答案:

答案 0 :(得分:0)

main.js中,将app.listen调用放在!module.parent的测试中,如下所示:

if(!module.parent){
  app.listen(process.env.PORT, () =>
    console.log(`Example app listening on port ${process.env.PORT}!`),
  );
}

来源:http://www.marcusoft.net/2015/10/eaddrinuse-when-watching-tests-with-mocha-and-supertest.html

答案 1 :(得分:0)

"testwatch": "nodemon --exec \"mocha --recursive\""

100%满足您的目的,直到测试库发布更相关的内容

答案 2 :(得分:0)

这看起来很hacky,但对我有用的是确保对于每组测试,我将使用不同的端口。

答案 3 :(得分:0)

较早的链接

if (!module.parent) {

从 v14.6.0、v12.19.0 开始弃用。 (documentation link)

一种解决方案是使用以下方法:

if (require.main === module) {

答案 4 :(得分:-1)

这意味着端口3000上已经有东西在运行。您需要停止该操作,然后启动您的应用程序。或者只是将应用程序的端口更改为其他端口。

要释放端口3000,请使用:

fuser -k 3000/tcp

kill $(sudo lsof -t -i:3000)

更改应用程序的端口:

var port = 8000;
app.listen(port, () =>
  console.log(`Example app listening on port ${port}!`),
);