I'm using mongodb-memory-server package and am having some trouble getting my async jest tests to run properly. I have a beforeAll that connects to a memory mongo database:
beforeAll(async () => await connect());
then I have an async test:
it("creates a new user", async () => {
const userObj = {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
phoneNumber: "+14444444444",
uid: faker.random.uuid(),
};
const userRes = await axios.post(routeUrl + "/", userObj);
const createdUser = userRes.data.user;
expect(createdUser._id).toBeTruthy();
});
the issue is that my test always times out when it is both async and includes an endpoint that modifies some data using the mongodb-memory-server. If I were to remove the async and put the logic after userRes
in a .then, the test passes. If I keep the async/await but wrap the code inside the test in a 1000ms async timeout, the test passes. Any thoughts on why the test is timing out in this current format shown above?
Here is an example of a passing version of the test:
it("creates a new user", () => {
const userObj = {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
phoneNumber: "+14444444444",
uid: faker.random.uuid(),
};
axios.post(routeUrl + "/", userObj).then(
userRes => {
const createdUser = userRes.data.user;
expect(createdUser._id).toBeTruthy();
}
);
});
.then
isn't returning the promise and so jest isn't waiting for it to "pass the test". You can also confirm the checks run by adding a jestjs.io/docs/en/expect#expectassertionsnumber check. – dcwither