I am using dotenv
to load an environment variable which is intended to be an API Token. All requests made to this API are valid only if they carry this token in a header.
I've already tried using:
require("dotenv").config();
in my app.js
file and also wrote my start script as:
"start": "node -r dotenv/config ./bin/www"
being the two recommended ways to load the environment variables in a .env
file.
Using both approaches, my API_TOKEN
environment variable is available at app.js
, as expected.
I am using Jest for testing, although I prefer Mocha and always use it. Saying this is relevant for people to understand why I am not sure my problem is due to Jest or not.
I have this test:
test("POST /cpf/* should fail when authorization token is wrong", async() => {
const data = { cpf: "927.059.107-78" };
await supertest(app)
.post("/cpf/verify")
.set("authorization","c68d357aaaaa8d82a29bade16ece0a1e")
.send(data)
.expect(500)
.then(async (response) => {
expect(response.body.mensagem).toBe("Request not authorized => invalid token.")
})
});
and this test is specific to this middleware:
router.use(function (req, res, next) {
let { authorization } = req.headers;
if (authorization !== process.env.API_TOKEN) {
res.status(500).send({ mensagem: "Requisição não autorizada => token de autorização inválido." });
}
next();
});
As you may see, it should block all requests when the authorization
token is different from the one stored in my .env
file.
It happens that process.env.API_TOKEN
is undefined
, but it shouldn't be!
I run out of ideas about this. Any suggestions?