【问题标题】:Jest has detected the following 1 open handle potentially keeping Jest from exitingJest 检测到以下 1 个打开的句柄可能会阻止 Jest 退出
【发布时间】:2019-03-13 01:29:18
【问题描述】:

这是我的 HTTP 路由

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

app.post('/sample', (req, res) => {
    res.status(200).json({
        x:1,y:2
    });
})

我想测试以下内容

1) GET 请求工作正常。

2)/sample 响应包含属性和xy

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

describe('Test the root path', () => {
    test('It should response the GET method', () => {
        return request(app).get('/').expect(200);
    });
})

describe('Test the post path', () => {
    test('It should response the POST method', (done) => {
        return request(app).post('/sample').expect(200).end(err,data=>{
            expect(data.body.x).toEqual('1');

        });
    });
})

但我在运行测试时遇到以下错误

Jest 检测到以下 1 个可能保留 Jest 的打开句柄 从退出:

返回请求(app).get('/').expect(200);

【问题讨论】:

    标签: javascript express testing jestjs


    【解决方案1】:

    你需要在end()方法中调用done()

    const request = require("supertest");
    const app = require("../app");
    
    let server = request(app);
    
    it("should return 404", done =>
        server
            .get("/")
            .expect(404)
            .end(done);
    });
    
    

    【讨论】:

      【解决方案2】:

      这招奏效了;

      afterAll(async () => {
          await new Promise(resolve => setTimeout(() => resolve(), 500)); // avoid jest open handle error
      });
      

      github issue 中所述。

      【讨论】:

        【解决方案3】:

        您好,您也可以使用 toEqual 函数

        describe('Test the post path', () => {
            test('It should response the POST method', () => {
                return request(app).post('/sample').expect(200).toEqual({ x:1,y:2
                });
            });
        })
        

        有很多方法可以代替。你可以去扔官方文档,其中涵盖了每个笑话功能https://jestjs.io/docs/en/expect

        【讨论】:

        • 试过你的答案,但我收到了这个错误Jest did not exit one second after the test run has completed
        • 你可以去扔文档,有几种方法。实际上,您需要的是调用方式。我从未在 Jest Testing 中使用过 return request(app)。我主要使用了expect(调用函数).toEqual(测试它的值),它对我来说非常好
        • 我在询问来自 http post 调用的 HTTP 响应
        【解决方案4】:

        作为调试此错误的一般提示,将 --detectOpenHandles 添加到运行 Jest 的 npm 脚本中,例如

           "scripts": {
            ...
            "test": "jest --detectOpenHandles"
            }
        

        这应该可以准确地告诉您代码的哪一部分导致了问题(可能是某种类型的服务器连接,特别是如果它的async)。

        一般来说,如果您可以将连接代码移动到测试之外的文件中的单独函数中,然后在测试中导入并调用它,这也将解决问题。

        【讨论】:

          猜你喜欢
          • 2021-09-26
          • 2020-09-20
          • 2020-08-24
          • 1970-01-01
          • 1970-01-01
          • 2019-06-30
          • 2021-06-13
          • 2020-11-13
          • 2018-11-14
          相关资源
          最近更新 更多