[英]Environment variable not available in a route while using NodeJS + Express and testing with Jest + Supertest
我正在使用dotenv
加載一個旨在成為 API 令牌的環境變量。 對這個 API 的所有請求只有在 header 中攜帶這個令牌才有效。
我已經嘗試使用:
require("dotenv").config();
在我的app.js
文件中,還將我的啟動腳本寫為:
"start": "node -r dotenv/config ./bin/www"
作為在.env
文件中加載環境變量的兩種推薦方法。
使用這兩種方法,我的API_TOKEN
環境變量在app.js
可用,正如預期的那樣。
我正在使用 Jest 進行測試,盡管我更喜歡 Mocha 並且一直使用它。 說這與人們理解為什么我不確定我的問題是否由 Jest 引起有關。
我有這個測試:
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.")
})
});
此測試特定於此中間件:
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();
});
如您所見,當authorization
令牌與存儲在我的.env
文件中的令牌不同時,它應該阻止所有請求。
碰巧process.env.API_TOKEN
是undefined
,但不應該是!
我對此沒有想法。 有什么建議么?
這里的重點根本不是 Jest,而是我的目錄結構。
我正在使用這樣的結構:
project_home/
|
|-- node modules (only with Jest and Supertest)
|-- package.json (only with Jest and Supertest)
|-- package-lock.json (only with Jest and Supertest)
|-- __tests__/ (directory with the Jest test suites)
|-- api (Express application)
|
|-- Dockerfile
|-- node modules (all app dependencies)
|-- package.json (all app dependencies)
|-- package-lock.json (all app dependencies)
|-- .env (environment variables)
|-- app.js (app main file)
|-- routes/ (routes directory)
當我這樣做時,我的想法是隔離測試並僅對應用程序進行 dockerizing,而沒有測試代碼。 正如我發現的那樣,這種方式行不通。
當我將__tests__
目錄移動到api
目錄時,我的測試用例可以立即訪問所有環境變量。
project_home/
|
|-- api (Express application)
|
|-- __tests__/ (directory with the Jest test suites)
|-- Dockerfile
|-- node modules (all app dependencies)
|-- package.json (all app dependencies)
|-- package-lock.json (all app dependencies)
|-- .env (environment variables)
|-- app.js (app main file)
|-- routes/ (routes directory)
作為獎勵,我可以刪除文件package.json
、 package-lock.json
和我的project_home
目錄中的目錄node modules
,因為它們不再需要了。 我只需要使用:
npm i jest --save-dev
和
npm i supertest --save-dev
在我的api
目錄中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.