New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Jest did not exit one second after the test run has completed. #7287
Comments
Try putting "done" inside the callback from the test function as so:
Additionally, if a connection is being kept open, this will also stop the test from completing, so closing any open connection would be recommended as well. |
Thank you ExoMemphiz, but this callback, from where should I reachit? It's too deep inside the server. I moved to Ava, it works out of the box 👍 |
Well well, my danish brother :) The problem is that I'm using mongoose to save something async when I call this api, and I cannot reach this code to figure out when it's finished saving the document inside mongo. await server.inject The code above actually wait for the response only, and it works, but jest complain about the mongoose save, it still in progress saving behind the scene. I tried to disconnect mongoose, and close each connection, but it doesn't work. |
I was getting the same error in one of my integration tests. In it, I was using a Sequelize Model to setup the database to a known state in EDITED: And by popular request, here is effectively what I've done: # dbConnection.js
export default new Sequelize({...}); // The Sequelize instance. # some.spec.js
import dbConnection from './dbConnection';
const { SomeModel } = dbConnection.models;
describe('...', () => {
beforeEach(async () => {
await SomeModel.create({...});
});
...
});
afterAll(async done => {
// Closing the DB connection allows Jest to exit successfully.
dbConnection.close();
done();
}); I added an example. |
What version of Sequelize are you using? I get |
Can you show your code? |
Hi, I was getting the same error, with @dhurlburtusa tip, my code was @AnitaMartinez, I'm new in TypeScript, so I'm pretty sure this can be done in a better way:
The |
I was getting the same error in one of my integration tests. In it, I use
|
Had this problem with tests that used firebase. This fixed it:
|
If you've multiple test files, I use global setup and teardown. For example in module.exports = {
globalSetup: './setupTests.js',
globalTeardown: './teardownTests.js',
}; In |
I was having this problem with Knex and using global setup and teardown files on Jest. My solution was: // setup.js
const knexConfiguration = require('../config/knex')[process.env.NODE_ENV];
const knex = require('knex');
const setup = async () => {
const client = knex(knexConfiguration)
await client.migrate.latest();
await client.destroy();
};
module.exports = setup; // teardown.js
const knexConfiguration = require('../config/knex')[process.env.NODE_ENV];
const knex = require('knex');
const teardown = async () => {
const client = knex(knexConfiguration)
await client.migrate.rollback();
await client.destroy();
};
module.exports = teardown; Hope it helps anybody facing this kind of problem. |
Hello everyone, Please correct me if I'm wrong but this seems like an issue which is not on Jest's side. If you want the tests to exit even when there are external resources being held I think you should use
As the author mentioned, it's possible to use Given the arguments above, perhaps this issue could be closed? |
@lucasfcosta Every time I've tried using |
Is there any other way to debug? |
Same here. I get no output from
My jest.config.js: module.exports = {
bail: true,
collectCoverage: false,
collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/index.tsx', '!src/main.ts', '!**/node_modules/**'],
coverageDirectory: '<rootDir>/coverage',
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx'],
rootDir: process.cwd(),
testMatch: ['<rootDir>/src/**/*.test.{ts,tsx}'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
verbose: true,
}; My test case: import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
}); |
For anyone running into this using afterAll(async done => {
await models.sequelize.close();
done();
}); That fixed the issue. |
I'm testing Jest with mongoose and supertest, add |
Another possible reason I faced – not closed Redis connection. afterAll(async done => {
globalRedisClient.unref();
done();
}); |
My solution won't work for everyone, but if you scoured the web for as long as I did trying to figure out how to close that damn handle that was left open, this might help. In my ecosystem, we are running a Parse Server as middleware with an Express server, but this could apply to anyone who needs to run a separate server with the tests but is unable to close some socket or port at the end. I believe the issue causing the dreaded "Jest did not exit one second..." error for us was a result of Parse's MongoDB adapter not closing correctly. So to get around this issue, I abstracted the server initialization completely out of the jest test suite and created a special npm script to run it in an entirely separate process. NPM Script (package.json):
listen_on_port_5000.sh
So how does this work?
|
I had tests that were checking auto generated http server and socket.io connections. I was closing both the socket.io server and http server correctly at the end of the test, but I was not closing the clients. Once I added the cleanup for the clients, the tests exited successfully on their own on both my dev machine and CI server. The tests would work without closing the clients if I used I also found that |
I have run into the same issue with
|
Facing same issue tried closing sequelize connection , no luck there. |
I've been having this problem too I ended up using https://www.npmjs.com/package/why-is-node-running logging in beforeAll import log from 'why-is-node-running';
afterAll(async () => {
//normal cleanup things
await new Promise(resolve => {
setTimeout(() => {
log()
resolve()
}, 4000)
})
} turns out that since I was using jest.resetModules, I had to reimport the module that was using a pg connection and close it there too. |
I'm also having this problem. To give some context, I am using SuperTest to do some e2e testing with let mongoServer;
beforeAll(async (done) => {
mongoServer = new MongoMemoryServer({ instance: { port: 26016 } });
const uri = await mongoServer.getUri();
process.env.MONGODB_URI = uri;
done();
});
afterAll(async (done) => {
await mongoServer.stop();
done();
}); Nothing out of the ordinary that would suggest that I'm following the documentation wrong. I'm going to investigate further by sampling the node processes and see exactly what spawns them. I will update here with my findings. EDIT: Related issue #1456 - it looks like it's an underlying NodeJS issue. tl;dr - add the |
I am having this error on several jest tests. I am closing express server properly with server.close(). On a test i solved the problem closing a mongoose connection properly using connection.disconnect(). But other tests are presenting the message yet. I noticed that all my tests that uses the supertest package keeps the message. The way is to analyze case by case. |
What if I'm not calling a database ? What if I'm calling an external resource of which I have no control ? How do I "close" ? |
@YounesTea you might have an async/await call in your code. it("Should test something", async (done) => {
// Sends request...
const req = await request(app).get("/someEndpoint");
expect(req).toBeTruthy();
done();
}); |
I have async/awaits and i am already using the done() callback on the tests including beforeAll and afterAll. |
That doesn't work. However, this one works: afterAll(async () => {
await app.delete()
}) |
in mongo i solved this:
|
This solution appears to be somewhat generic. We're using a postgres conn pool and starting to use Jest. I did this afterAll(async () => { Kind of obvious after you realize that the DAO modules are using a shared connection pool, and only the service itself should end() the pool. |
The solution is generic indeed, each one has it's cases, the problema is |
This is what ended up working for me (most of the time). I was running an API server and doing end to end testing with puppeteer. I needed a await global.server.destroy();
spawnSync('kill', ['-9', global.server.pid], { shell: true, cwd: cwd() }); That being said, --detectOpenHandle is def broken. |
Hey, i think i'm having the same issue, im currently trying to test a node express app using typescript and for testing i'm using jest and supertest and im getting the same errors, could you tell me how can i close the redis connection? tried importing redis and redisClient but couldnt find the unref() method |
Thansk!! It really makes sense that we have to close the connection after tests are done, you're awesome! |
After losing hope to Now, Previously I was simply mocking (
To solve this, I have changed the way to mock the client library as per the requirement. The following way of mocking has worked successfully.
You can include more functions ( I hope this helps 🙏 |
It's extremely disappointing that after almost 3 years there seems to have been zero effort to resolve this issue and make detection of unresolved promises any easier. Ideally node itself would make this an easier issue to debug. I don't know how many days I've lost over the years trying to debug these kinds of issues. |
I have a similar problem with a database connection with knex. After call connection.destroy() on afterAll(), the message has gone. |
If you tried all different solutions above and none of them works for you, this probably because you're using an in-memory database, something like this:
Which I don't know how to solve it either! |
Adding jest.useFakeTimers(); at the beginning of the test suite fixed it for me. Might come from timers defined in components part of the render (like throttled buttons, mocks etc..). |
--watchAll=false in ci environment |
Node.js has an API Would be very helpful. |
This issue is stale because it has been open for 1 year with no activity. Remove stale label or comment or this will be closed in 30 days. |
AFAIK this hasn't been fixed |
This is the solution for the problem. |
I was able to fix the issue for me in this way. 🥳 I first ran my test package.json script with the additional command of So I could see which node processes are running after jest process has been finished. To verify if my assumption is correct I closed intelliJ and my MS Teams Client and started the same script in my terminal. To be double assure I startet my MS Teams Client again and startet the test script in my terminal again. Conclusion: |
Fixed for me by closing my server and puppeteer browser before running the expect tests. expect(messages).toMatch(expectedMessages);
await server.close();
await browser.close(); This worked: await server.close();
await browser.close();
expect(messages).toMatch(expectedMessages); Seems like Jest got stuck after a failed test and never got to server.close(). |
For those experiencing this when working with Firebase, you likely need to call testEnv.cleanup();
|
I'm getting this message every time i'm using any libraries that depend on promises.
🐛 Bug Report
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with
--detectOpenHandles
to troubleshoot this issue.To Reproduce
I have a function that need to make a request to external api, and in the same method just save in the database without waiting for a response.
I don't want to wait until the saving process is done, but i'm forced to change the behaviour of my application to get it tested through jest., or i need to close the connection, stop the server for my code to work.
Expected behavior
Excecpted jest to stop and return to my console.
Link to repl or repo (highly encouraged)
line49 and line50
I had to make those changes to get jest working with my api server and mongodb.
jamalsoueidan/giv-et-tilbud@d8f326b
Run
npx envinfo --preset jest
The text was updated successfully, but these errors were encountered: