【问题标题】:Node EADDRINUSE: address already in use :::3000 when testing with jest and supertest节点 EADDRINUSE:使用 jest 和 supertest 测试时地址已在使用 :::3000
【发布时间】:2020-07-03 07:21:21
【问题描述】:

我正在尝试用 jest 和 supertest 测试我的 API 端点:

我的测试路线文件:

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


describe('test app endpoints', ()=>{
    test('index should return 200 code', async (done) =>{
        const response = await request(app).get('/')
        expect(response.statusCode).toBe(200)
        done()
    })

index.js:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

const port = 3000


app.set('view engine', 'ejs')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use('/', require('./routes/conversions'))

module.exports = app.listen(port, (err) => {
    if (err) throw err
    console.log(`Server is running on port ${port}`)
})

当我运行这个测试时,我收到关于占用端口的错误:

listen EADDRINUSE: address already in use :::3000

我怎样才能解决这个问题并且不阻止我的端口进行测试?

【问题讨论】:

  • 使用不同的端口?你真的不应该使用低于 8000 左右的端口号。
  • 我尝试将我的端口号更改为其他内容,但我得到了同样的错误,但使用了新的端口号。
  • 它是否试图多次启动您的应用程序?因为那是行不通的......

标签: javascript node.js jestjs supertest


【解决方案1】:

您计算机上的其他东西正在使用端口 3000;就这样。只需将port 变量设置为其他值; 8080 和 8000 是受欢迎的选择。

【讨论】:

  • 不幸的是,这不是问题,因为“lsof -i :3000”不会返回在该端口上运行的其他程序。我相信这是玩笑或超级测试的问题,他们多次运行这些端口。我试图将我的端口号更改为其他内容,但我得到了同样的错误,但使用了新的端口号。
  • 只是为了确认一下,代码在你运行node index.js时有效?
【解决方案2】:

这个问题实际上与您在测试环境中运行服务器的方式有关。 解决此问题的一个简单方法是将 app.listen() 包装在一个条件中,以检查环境是否为测试环境。在测试环境中,通过 Supertest 运行服务器时,不需要让应用监听网络端口。 因此,通过向 index.js 添加条件检查来解决此问题:

if (process.env.NODE_ENV !== 'test') {
    app.listen(port);
}

更多信息请阅读this

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2019-10-11
    • 2021-05-14
    • 1970-01-01
    • 2016-05-12
    相关资源
    最近更新 更多