I am trying to write test code for a project management software using Jest. The software is written with Javascript, and uses MongoDB for the database. The project uses an object model hirecarchy that goes:
User => Project => Backlog => Story => Task
I use an external script to populate the test database before running the tests in the test file using a beforeEach block. So far, the populate script makes a couple of users. Then assigns a couple of projects to a chosen user. Then assigns a couple of backlogs to a chosen project. Then assigns a couple of stories to a chosen backlog.
This method has worked for the tests on the user to the backlog model. Now I am writing the test for the story model and I am running into a problem where by the time the code in the test block is executing, the test database is not completely populated.
I have used breakpoints and MongoDBCompass to see what is in the database by the time the code is in the test block, and it appears that database is populated to varying extents during it run. It seems as though the code populating the database is lagging jests execution queue. Is there anyway I can ensure the database population is done before I enter the test block?
Before each block in the story model test file
beforeEach( async () => {
await User.deleteMany();
await Project.deleteMany();
await Backlog.deleteMany();
await Story.deleteMany();
populate.makeUsers();
populate.assignProjects(userXId, userX.userName);
populate.assignBacklogs(populate.projects[1]);
await populate.assignStories();
await new User(userX).save();
});
The function populating the database with Stories
this.assignStories = async function () {
const pBacklog = await Backlog.findOne({project: this.projects[1]._id, name: "Product Backlog"})
const temp = this
if (pBacklog != undefined) {
let pBacklogID = pBacklog._id
this.stories = createStories(14, this.projects[1]._id, pBacklogID, this.backlogs[0]._id);
this.stories.forEach(async (story, index) =>{
let newStory = new Story(story);
this.stories[index] = newStory;
await newStory.save();
})
} else {
setTimeout(async function () {await temp.assignStories()}, 200)
}
}
I have excluded the functions for populating the other models to keep this short but I can add it if it will help with the problem.
Thank you.