(Junior dev here :) )
Hi!! i m having problems running endpoints test with Jest. Just to let you be aware the endpoint i 'll show you is working because i test it manually with a http file.
node version = v18.8
My models in package.json(for the versions):
"scripts": {
"test": "jest --detect-open-handles"
},
"devDependencies": {
"@types/jest": "^29.0.0",
"eslint": "^8.21.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-jest": "^27.0.1",
"jest": "^29.0.1",
"prettier": "^2.7.1"
the endpoint (a register):
router.post("/register", validator.authentificationValidation, hashPseudo,async (req, res, next) => {
let salt = bcrypt.genSaltSync(10);
let user = req.body;
if (user.pseudo == null || user.password == null) {
res.status(400).json({
error: "Missing fields",
});
return;
}
try {
user.password = bcrypt.hashSync(user.password, salt);
let check_user = await userQuery.getByPseudo(user.pseudo);
if (check_user.length != 0) {
res.status(400).json({
msg: "Account already exists",
});
return;
}
await userQuery.add(user);
let result = await userQuery.getByPseudo(user.pseudo);
let token = jwt.sign({ userId: result[0].id }, process.env.SECRET);
res.status(200).json({ token: token });
} catch (err) {
return next(err);
}
}, );
The test with jest:
const axios = require("axios");
const API_URL = process.env.API_TEST_URL;
let TOKEN;
test("POST test register user", async () => {
const data = {
pseudo: "Activity_TEST",
password: "123",
date: "2021-09-29 16:31:25",
};
const url = `${API_URL}/register`;
const response = await axios.post(url, data);
expect(response.status).toBe(200);
expect(response.data).toHaveProperty("token");
TOKEN = response.data.token;
});
The error log:
Jest has detected the following 6 open handles potentially keeping Jest from exiting:
- TLSWRAP
14 | };
15 | const url = `${API_URL}/register`;
> 16 | const response = await axios.post(url, data);
| ^
17 | expect(response.status).toBe(200);
18 | expect(response.data).toHaveProperty("token");
19 | TOKEN = response.data.token;
at RedirectableRequest.Object.
<anonymous>.RedirectableRequest._performRequest (node_modules/follow-
redirects/index.js:279:24)
at new RedirectableRequest (node_modules/follow-
redirects/index.js:61:8)
at Object.request (node_modules/follow-redirects/index.js:511:14)
at dispatchHttpRequest
(node_modules/axios/lib/adapters/http.js:262:25)
at httpAdapter (node_modules/axios/lib/adapters/http.js:49:10)
at dispatchRequest
(node_modules/axios/lib/core/dispatchRequest.js:58:10)
at Axios.request (node_modules/axios/lib/core/Axios.js:109:15)
at Axios.httpMethod [as post]
(node_modules/axios/lib/core/Axios.js:144:19)
at Function.wrap (node_modules/axios/lib/helpers/bind.js:9:15)
at Object.post (src/routes/data/activity/test.js:16:32)
if you reach until here. Thanks a lot :)