supertest: Open handle keeps Jest from exiting ( TCPSERVERWRAP)
Error:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPSERVERWRAP
Env:
- Node 10
- Supertest 3.3.0
- Jest 23.6
Testcode:
const request = require('supertest');
const app = require('../app');
describe('Test the status paths', () => {
test('The GET / route should give status code 200', async () => {
expect.assertions(1);
const response = await request(app).get('/');
expect(response.statusCode).toBe(200);
});
test('The GET /status route should give status code 200', async () => {
expect.assertions(1);
const response = await request(app).get('/status');
expect(response.statusCode).toBe(200);
});
});
Full console output:
PASS tests/app.test.js
Test if test database is configured correctly
✓ Jest should create a test database (54ms)
Test the status paths
✓ The GET / route should give status code 200 (28ms)
✓ The GET /status route should give status code 200 (7ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.179s
Ran all test suites.
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● TCPSERVERWRAP
27 | test('The GET /status route should give status code 200', async () => {
28 | expect.assertions(1);
> 29 | const response = await request(app).get('/status');
| ^
30 | expect(response.statusCode).toBe(200);
31 | });
32 | });
at Test.Object.<anonymous>.Test.serverAddress (node_modules/supertest/lib/test.js:59:33)
at new Test (node_modules/supertest/lib/test.js:36:12)
at Object.obj.(anonymous function) [as get] (node_modules/supertest/index.js:25:14)
at Object.get (tests/app.test.js:29:45)
^C
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 159
- Comments: 120
Commits related to this issue
- UPDATED: - AccountController 테스트 FIXED: - jest open handle error - https://github.com/visionmedia/supertest/issues/520#issuecomment-533643457 — committed to bbonkr/blog-node-backend by bbonkr 5 years ago
- progress on alternate test strategy suggested here - https://github.com/ladjs/supertest/issues/520\#issuecomment-436071071 — committed to RFP2210-SDC/API-RatingsReviews by ChadFusco 2 years ago
For me this did the trick
Seems like it needs some more ticks to close that handle.
@AlexisNava
Try this in your app.test
@lucianonooijen @danielantelo Sorry about that, I sometimes confuse the express app with the server object.
When supertest is used in an express application not yet bound to a port, it will try to automatically bound it to a random port, holding a reference to the net server internally. To gain control over that process, you may want to try manually listen on a port yourself, so that you can close the connections manually.
As an alternative to setting up an agent, you can also use the
end
method to force supertest to close the automatic bound connection.However, I am not sure how well this method plays with the promise based interface, because as you can see is expecting a callback.
References: https://github.com/visionmedia/supertest/blob/master/lib/test.js#L54
Hope it helps!
+1 i could use help with this issue also, same env as above and same errors.
None of the above mentioned worked for me but somehow below code worked
jest.config.js
test-teardown-globals.js
@jonathansamines I tried adding
and
but both give the same error:
Did I invoke them wrong or am I missing something somewhere?
I found out that if you are using process.env in any test it also won’t exit.
This was the solution for me.
Three years later and I still can’t get this to work. The most basic setup isn’t going for me: no databases, no extraneous middleware, no other resources.
I’ve tried any and all combinations of
.end(done)
,async
usages and manualserver
/agent
closing mentioned in this thread and nothing worked for me. Did anyone managed to get this running without leaking? Maybe even a false positive fromjest
?works too.
I have the same issue:
Node version: 11.0.0 npm version: 6.5.0
package.json
test task in package.json
app.test.js
Error:
thanks for the reply @jonathansamines , appreciate it! Still having issues tho.
This is my setupTestFrameworkScriptFile:
and then a test in another file:
my tests pass, but jest does not exit due to open handles in
global.agent.get('/get/all')
using
.end()
on the request does not work when using promises to assert values, i got the errorsuperagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises
.Any ideas what i am missing on the setup before/afters?
Much appreciated!
This is my case. I tested REST API endpoints as shown in example at Testing | NestJS.
The problem code is
And the solution is to use
await
instead ofreturn
:@lucianonooijen Does it works if you manually invoke
app.close
after each test? (either by individually calling it, or through aafterEach
block)Thanks, this work for me
For me, it was solved with a condition for adding the listener to the app if not ‘test’. Jest run as NODE_ENV=test
And for avoiding this warning (https://github.com/lorenwest/node-config/wiki/Strict-Mode), I added a config json file with
"env": "test",
.Here is my solution.
index.js
test.js
describe(‘AppController (e2e)’, () => { let app: INestApplication;
beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile();
});
it(‘/ (GET)’, () => { return request(app.getHttpServer()) .get(‘/’) .expect(200) .expect(‘Hello World!’); });
it(‘/weather (GET)’, () => { return request(app.getHttpServer()) .get(‘/weather’) .expect(200) .expect(‘weather’); })
afterEach( async () => { await app.close() }); });
The key for that is to add
I eliminated my open handle errors by restarting my pc.
But restart in my case helps for only one run of tests only. Then errors are back.
I use --forceExit combined with --detectOpenHandles flags to be sure that this doesn’t occur.
just remove --detectOpenHandles from command. prev: “test”: “jest --forceExit --detectOpenHandles --maxWorkers=1 --verbose” next: “test”: “jest --forceExit --maxWorkers=1 --verbose”
This worked well for me …
However, I had to make the following changes to my server file:
The above change means that the server still starts when you run
npm start
but does not start the normal server when you are testing.My npm start command from package.json is:
I am experiencing the same error. I suppose a solution for the time being is to use --forceExit with Jest.
I had the same issue. I was providing both
--detectOpenHandles
and--forceExit
, then I removed--detectOpenHandles
and now it’s working. Though, I would love to see the best way to fix this.Tried this out but ran into a couple of issues that I think is caused by this:
--watchAll
–maxWorkers=1 fixed all my issues
Start Server
Close Sever
I added this condition around app.listen process.env.NODE_ENV !== ‘test’. Works like charm
I found simple open handle keeps case and that solution.
Open handle keeps case test code
Open handle keeps result
Success case test code
Success result
I think this case is Jest probrem. Because it’s not mentioned in the manual.
This is working for us to get around this issue. Seems like something doesn’t shutdown in the same tick as it should.
This didn’t helped me. But I manged to force Jest to exit with this flag:
--forceExit
However I am still getting the warring that Jest detected an open handle.
For people who’re testing
Strapi
+supertest
, I’ve realized that to prevent this log, I need todestroy
all connections onafterAll
:According what I know, await should not work work with done
I literally just wasted 4 hours on this, had to use several of the solutions mentioned here. What FINALLY worked for me after literally trying every single one of them was a combination of @tksilicon solution + @lukaswilkeer + @carlafranca
To summarize I use the timeout in the afterAll, and I pass in --forceExit --detectOpenHandles --maxWorkers=1 and it finally worked.
I tried each of these on their own, but still had issues. The port mapping solution that so many had luck with did absolutely nothing for me either.
@sharmaar12 @angristan I don’t know the reason for sure, because I’m not familiar with the supertest code base. I guess that during the shutdown of supertest, somewhere the thread is not waiting for an async system operation to finish. Thus, the operation is delegated to the system but the execution is not blocked or does not wait for the async operation to finish. In the meantime, your test case execution finishes, jest is shuting down, and complains about an open handle.
If I’m wrong, please someone corrects me 😃
I was having similar issue with Mongoose and getting
TLSWRAP
with an open handle for a test looks as simple as this:Simply connecting and disconnecting from Mongoose was causing issues. 👇
I’ve tried pretty much all suggestions here. Adding a setTimeout in
afterAll
did not work at all. But adding setTimeout inbeforeAll
just before the mongo connection did work, like so:☝️ Notice the duration for setTimeout does not have to be more than 1 ms. This smells like a process nextTick issue somewhere. Meanwhile Mongoose website screams to not use Jest with Mongoose apps and not to use global setups and not to use fake timers etc… But of course I didn’t listen and thought what could go wrong. Now ended up wasting hours…
Solution
I am not fan of using timers to fix things, so for now I am moving forward with just calling disconnect in
beforeAll
to disconnect just in case there is anything there, like so:I am hoping this holds for me and helps anyone else out there 🤙
For some reason, removing
--detectOpenHandles
worked in two different contexts. This errormostly occurs when
.send({...})
is called.This worked!
package.json
server.ts
test-file1.ts
test-file2.ts
Sounds weird, but this is how it worked with me!
@rimiti this is by far the most requested feature (bugfix really), especially when considering the activity on these two issues which have the same root cause. https://github.com/visionmedia/supertest/issues/437 https://github.com/visionmedia/supertest/issues/436
If you are unable to provide the solution anytime in the near future, would you be able to give some guidance on where to start in the codebase so someone from the community is more likely to pick this up?
Or do you think this might be an issue with Jest and not supertest?
WHAT?! that seems super weird – do we know why?
Were any other solutions found for this issue? I have a similar problem. When I run my test suite normally, I get the warning that Jest did not exit one second after completion of the test run.
Calling with
--detectLeaks
finds a leak, and calling with--detectOpenHandles
shows the same issue - TCPSERVERWRAP.If I add @yss14 's code in the
afterAll
hook, something peculiar happens - running Jest normally still shows the open handle issue. Running with the--detectLeaks
flag still shows a leak. Running with--detectOpenHandles
shows nothing.I’m testing a middleware function, and my suite looks like this:
Binding to a port and closing manully does not work, nor does getting rid of
async/await
, and instead passingdone
intoend
(i.e passing not calling, so.end(done);
.Does anyone have any ideas? This is a serious issue because it seems that every test suite that relies on Express/Supertest is leaking memory, eventually to the point that my tests terminate with a
JavaScript heap out of memory
error.Thank you.
I tried all candidate solutions mentioned here. Thanks all for share. It seems that there is an odd behavior with Mongoose and an internal
nextTick
call, so finally I solved the problem by adding anextTick()
before calling the POST.I was having this issue and eventually traced it back to an issue with Jest and its
useFakeTimers
option, which I was using to mock the date.If you are using
jest.useFakeTimers()
, to mock the date/time, try an alternative such as mocking manually as there appears to be an issue with jest’s new/“modern” implementation of fake timers that doesn’t play nice with async.@jonathansamines 's first solution worked for me.
Here is an working example with async/await syntax of it:
For me, it was solved with a condition for adding the listener and mongoose
Jest has detected the following 1 open handle potentially keeping Jest from exiting: ● TLSWRAP
npm run test
I too would like to see a great way to fix this. From someone who has a complete understanding of why it happens. This person could describe the optimal and clean solution.
Hello ! I just had the problem and fixed it (I think). I fixed it this way:
I made the http server starting listening (just did
server.listen()
) before passing the server to supertest (instead of letting supertest making it listening), and I close/destroy the server myself afterwards.In my case, all I did to solve the problem, was install weak-napi as a dev dependency and then set detectLeaks and detectOpenHandles to true in my jest config file like so:
Finally this worked for me, hope this helps to others. I’ve been banging my head for hours, even the simplest tests with supertests were always kept hanging.
And by the way, how did I find it? by using https://www.npmjs.com/package/leaked-handles.
Passing done to the test and invoking it at the end resolved this for me, as mentioned by @soultoru above.
@cif The issue is not usually caused by
express-session
itself, but rather by the particular store used. I usually rely on the defaultMemoryStore
on tests, if it is really hard to properly shutdown the upstream connection to the store.@jonathansamines And I just wanted to make sure you know that I really appreciate your help and time. I have many test suites, and they’ve been taking a long time to compete, as well as all new test cases throwing a
JavaScript heap out of memory
error. I expect that will all be fixed now considering the heap should stop being bloated by open connections.With the memory leak issue hindering me, I considered moving on with building the rest of the API without code coverage, so thank you very much for saving my TDD endeavor.
@JamieCorkhill Yes please, await gor that one as well. I just forgot to await for it.
Hi @JamieCorkhill I finally got some time to take a look. After some debugging, I noticed there was an open mongodb connection, which was never closed.
See a couple of changes I made to your example: https://github.com/JamieCorkhill/Jest-Memory-Leak-Repro/compare/master...jonathansamines:master
But, in summary:
request
directly.@jonathansamines I did try solution proposed in the comment you linked to, but I recieve the same response:
Running with
--detectOpenHandles
does not find anything.The
auth.test.js
file contains only three tests:I can try to create an isolated repro example, but you’ll need a local MongoDB Server running.
Thank you.
got it working with just jest/supertest/mongoose (removing mockgoose). Thanks for the help.
Now time to figure out the issue with mockgoose 😂