【发布时间】:2018-12-24 16:31:14
【问题描述】:
我目前面临一个无法解决的错误,并且我已经苦苦挣扎了几个小时。
我正在使用以下版本:
节点:8.11.3
快递:4.16.3
开玩笑:22.2.2
猫鼬:5.2.3
我正在尝试使用 jest 进行一些集成测试,并且我有 2 个带有测试的文件。
在每个文件中,我写了以下内容:
// Create the server before each test.
beforeEach(() => {
server = require('../../index');
});
// Close the server after each test.
afterEach(async () => {
if (server) {
server.close();
}
});
在index.js我有以下(这不是所有代码,而是bug的相关代码):
// Listen to the server.
const port = config.PORT || process.env.PORT || 3000;
module.exports = app.listen(port, () => {
winston.info(`Listening to port ${port}...`);
});
当我运行 npm test
我总是得到这个异常:
**listen EADDRINUSE :::3000**
10 | // Listen to the server
11 | const port = config.PORT || process.env.PORT || 3000;
> 12 | module.exports = app.listen(port, () => {
13 | winston.info(`Listening to port ${port}...`);
14 | });
15 |
我尝试了几种方法来解决这个问题,将async await 添加到beforeEach 和afterEach 并尝试将sever.close 放入afterAll 和beforeAll,但仍然遇到相同的错误。
然后,我尝试通过这样做来解决:
How Do I Shut Down My Express Server Gracefully When Its Process Is Killed?
但同样,没有运气。
最后,当我在 1 个文件中编写所有测试时,没有这个 error 就可以工作。有谁知道如何解决这个问题?我不想在 1 个文件中编写所有集成测试。
谢谢!
【问题讨论】: