I have a simple controller for adding new users. After the successful resolution (user added), the controller sends a 202 response. As you can see, the function is promise based and is not using async/await.
const addUserController = function (req, res, next) {
Users.addOne(req.userid, req.body.email)
.then(() => {
res.status(202).send();
})
.catch((err) => {
console.log(err);
res.status(500).json({ message: "Internal server error." });
});
};
When I am testing this function in Jest with the, the function executes immediately, without going to the then() part, resulting in a mistaken 200 code, instead of 202, so the following test fails:
it("Should add a user", () => {
let req, res, next, pool;
pool = new Pool();
req = httpsMocks.createRequest();
res = httpsMocks.createResponse();
res.next = null;
req.userid = 1;
req.body = {
id: 2
}
pool.query.mockResolvedValue({rows:[], rowCount: 1});
apiController.addUserController(req, res, next);
expect(res.statusCode).toBe(202);
expect(pool.query).toBeCalledTimes(1);
});
However, when I make it like that:
it("Should add a user", async () => {
let req, res, next, pool;
pool = new Pool();
req = httpsMocks.createRequest();
res = httpsMocks.createResponse();
res.next = null;
req.userid = 1;
req.body = {
id: 2
}
pool.query.mockResolvedValue({rows:[], rowCount: 1});
await apiController.addUserController(req, res, next);
expect(res.statusCode).toBe(202);
expect(pool.query).toBeCalledTimes(1);
});
that is I add async/await, it works alright – the response status code is 202, meaning the function was awaited and the test passes.
But why? When I hover over the newly added ‘await’ VS code is suggesting that
‘await’ has no effect on the type of this expression.
Well it makes sense – it should have no effect, as the tested function is not async, so it shouldn’t work, but well, it works – only when I add the async/await to the Jest function it works fine.
Could someone explain this to me?