Jest 检测到以下 1 个打开的句柄可能会阻止 Jest 退出

iam*_*man 6 javascript testing express jestjs

这是我的 HTTP 路由

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

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

我想测试以下内容

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');

        });
    });
})
Run Code Online (Sandbox Code Playgroud)

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

Jest 检测到以下 1 个可能阻止 Jest 退出的打开句柄:

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

小智 9

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

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

let server = request(app);

it("should return 404", done =>
    server
        .get("/")
        .expect(404)
        .end(done);
});

Run Code Online (Sandbox Code Playgroud)


Dav*_*wii 9

这个伎俩奏效了;

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

如本github 问题中所述。


Shr*_*oel -1

您好,您也可以使用 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
        });
    });
})
Run Code Online (Sandbox Code Playgroud)

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