mongo-mock
mongo-mock copied to clipboard
jest is not terminating, giving error when used jest with mongo-mock
I am getting below error when I run 'npm run test' :
"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."
Tried running jest with --detectOpenHandles but still the same issue. Below is my code :
var mongodb = require("mongo-mock"); mongodb.max_delay = 10; //you can choose to NOT pretend to be async (default is 400ms) var MongoClient = mongodb.MongoClient; MongoClient.persist = "mongo.js"; //persist the data to disk
// Connection URL var url = "mongodb://localhost:27017/myproject";
describe("test set", () => {
beforeAll(done => {
// Use connect method to connect to the Server
MongoClient.connect(
url,
{
sslValidate: false,
useNewUrlParser: true,
sslCA: fs.readFileSync("./rds-combined-ca-bundle.certs")
},
async function (err, client) {
if (err) {
debug(Failed to connect to the database. ${err.stack}
);
} else {
app.locals.dbClient = client;
done();
}
}
);
//done();
});
afterAll(done => { // Closing the DB connection allows Jest to exit successfully. try { app.locals.dbClient.db().close(); app.locals.dbClient.close(); done(); } catch (error) { console.log(error); done(); } // done() });
describe('POST request', () => {
test("test POST query", async () => {
var bodyData = mockData.test_SingleData;
var response = await request
.post(/
)
.send(bodyData);
expect(response.statusCode).toBe(200);
//done();
});
});
});
test case run successfully but somehow its not turminated,. Help please.
I have exactly the same issue.
My tests are hanging and if I log the steps I can see that the beforeEach
block isn't respecting your "async" code.
beforeEach((done) => {
const db = STUBS.mongoClient.db();
const collection = db.collection('foo'); // executes before the test. Good.
collection.insertMany(
[foo1, foo2],
() => {
const j = collection.toJSON(); // executes after the test... Bad!
done();
},
);
}, 10000);
Also with async, same behaviour
beforeEach(async () => {
const db = await STUBS.mongoClient.db();
const collection = db.collection('foo'); // executes before the test
await collection.insertMany([foo1, foo2]);
const j = collection.toJSON(); // executes AFTER the test...
});
Seems like some internal promise hacking is conflicting with jest.
this works for me:
describe('test using mongo-mock', () => {
var db, client;
beforeAll(async () => {
var mongoUrl = process.env.MONGODB_URL || 'mongodb://localhost:27017/myproject';
client = await mongoClient.connect(mongoUrl, {});
db = client.db();
var collection = db.collection('documents');
// prepare data ....
});
afterAll(() => {
db.close();
client.close();
});
// tests come here....
});