My goal is to validate a route within my Express
server using Supertest
. This particular route retrieves data from a MongoDB
, and the data is then sorted based on the updatedAt field.
While attempting to test the order of the output, I encountered an issue - it appears that some documents in the MongoDB have identical timestamps (which came as quite a surprise).
https://i.sstatic.net/eg9t3.jpg
How exactly is this sorting happening internally? It doesn't seem to be sorted by _id either. Here's the function from my test that generates these documents:
let first;
let last;
Array.from(Array(14)).forEach((e, i) => {
const immo = new Immo({ user: this.user.model });
immo.save();
if (i === 2) {
// identifying the last document with limit 12 sorted by descending timestamps
last = immo._id.toString();
}
if (i === 13) {
// marking the most recent document, which should appear first in the sorted list
first = immo._id.toString();
}
});
The resulting output comprises the last 12 items edited by the user. I store references to the earliest and latest documents for later assertion purposes.
However, the test fails due to several documents sharing the same timestamp, causing incorrect ordering. The document that was inserted last in the DB isn't necessarily appearing last when Mongo sorts by timestamps.
I even attempted introducing a delay within a for-loop during the input process, but it had no effect. (Is there a better alternative than using Array.forEach?)
Is there a way to ensure a minimum time gap between the documents to overcome this issue?