简体   繁体   English

使用 NodeJS + Express 并使用 Jest + Supertest 进行测试时,环境变量在路由中不可用

[英]Environment variable not available in a route while using NodeJS + Express and testing with Jest + Supertest

I am using dotenv to load an environment variable which is intended to be an API Token.我正在使用dotenv加载一个旨在成为 API 令牌的环境变量。 All requests made to this API are valid only if they carry this token in a header.对这个 API 的所有请求只有在 header 中携带这个令牌才有效。

I've already tried using:我已经尝试使用:

require("dotenv").config();

in my app.js file and also wrote my start script as:在我的app.js文件中,还将我的启动脚本写为:

"start": "node -r dotenv/config ./bin/www"

being the two recommended ways to load the environment variables in a .env file.作为在.env文件中加载环境变量的两种推荐方法。

Using both approaches, my API_TOKEN environment variable is available at app.js , as expected.使用这两种方法,我的API_TOKEN环境变量在app.js可用,正如预期的那样。

I am using Jest for testing, although I prefer Mocha and always use it.我正在使用 Jest 进行测试,尽管我更喜欢 Mocha 并且一直使用它。 Saying this is relevant for people to understand why I am not sure my problem is due to Jest or not.说这与人们理解为什么我不确定我的问题是否由 Jest 引起有关。

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.如您所见,当authorization令牌与存储在我的.env文件中的令牌不同时,它应该阻止所有请求。

It happens that process.env.API_TOKEN is undefined , but it shouldn't be!碰巧process.env.API_TOKENundefined ,但不应该是!

I run out of ideas about this.我对此没有想法。 Any suggestions?有什么建议么?

The point here wasn't Jest at all, but my directory structure.这里的重点根本不是 Jest,而是我的目录结构。

I was using a structure like this:我正在使用这样的结构:

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)

My idea, when I did this, was isolating the tests and dockerizing only the app, without the test's code.当我这样做时,我的想法是隔离测试并仅对应用程序进行 dockerizing,而没有测试代码。 It doesn't work this way, as I found out.正如我发现的那样,这种方式行不通。

When I moved the __tests__ directory to the api directory, all the environment variable got accessible immediately to my test cases.当我将__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)

As a bonus, I could remove the files package.json , package-lock.json and the directory node modules in my project_home directory, since they are not needed anymore.作为奖励,我可以删除文件package.jsonpackage-lock.json和我的project_home目录中的目录node modules ,因为它们不再需要了。 I just had to use:我只需要使用:

npm i jest --save-dev

and

npm i supertest --save-dev

inside my api directory.在我的api目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM