簡體   English   中英

使用 NodeJS + Express 並使用 Jest + Supertest 進行測試時,環境變量在路由中不可用

[英]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_TOKENundefined ,但不應該是!

我對此沒有想法。 有什么建議么?

這里的重點根本不是 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.jsonpackage-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM