test process.env with Jest

后端 未结 9 1942
南笙
南笙 2020-11-28 04:00

I have an app that depends on environmental variables like:

const APP_PORT = process.env.APP_PORT || 8080;

and I would like to test that fo

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:24

    You can use setupFiles feature of jest config. As documentation said that,

    A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

    1. npm install dotenv dotenv that uses to access env variable.
    2. Create your .env file to root directory of your application and add this line into it.
    #.env
    APP_PORT=8080
    
    1. Create your custom module file as It name being someModuleForTest.js and add this line into it.
    //someModuleForTest.js
    require("dotenv").config()
    
    1. Update your jest.config.js file like this
    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
    1. You can access env's variable within all test blocks.
    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    

提交回复
热议问题