Reputation: 5858
Here are my HTTP routes
app.get('/', (req, res) => {
res.status(200).send('Hello World!')
})
app.post('/sample', (req, res) => {
res.status(200).json({
x:1,y:2
});
})
I would like to test for the following
1) GET
request working fine.
2)the /sample
response contains the properties and x
and y
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');
});
});
})
But I got the following error on running the test
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
return request(app).get('/').expect(200);
Upvotes: 10
Views: 17991
Reputation: 31960
As a general tip to debug this error, add --detectOpenHandles
to your npm script that runs Jest e.g.
"scripts": {
...
"test": "jest --detectOpenHandles"
}
This should tell you exactly which part of the code is causing the issue (probably some type of server connection, particularly if its async
).
In general, if you can move the connection code to a separate function in a file outside of your tests, then import and call it in your tests, this will also fix the issue.
Upvotes: -2
Reputation: 7840
This trick worked;
afterAll(async () => {
await new Promise(resolve => setTimeout(() => resolve(), 500)); // avoid jest open handle error
});
As described in this github issue.
Upvotes: 9
Reputation: 197
you need to call done()
in the end()
method
const request = require("supertest");
const app = require("../app");
let server = request(app);
it("should return 404", done =>
server
.get("/")
.expect(404)
.end(done);
});
Upvotes: 11
Reputation: 897
Hi You can use the toEqual function as well
describe('Test the post path', () => {
test('It should response the POST method', () => {
return request(app).post('/sample').expect(200).toEqual({ x:1,y:2
});
});
})
There are lots of methods can be used instead.You can go throw the official documentation which covers every jest function https://jestjs.io/docs/en/expect
Upvotes: -1