To mock a value from .env.test
file in jest
test cases written in TypeScript, you can use the jest.mock
function in combination with the dotenv
package.
First, install the dotenv
package by running the following command:
index.ts19 chars2 lines
Then, in your test file, you can mock the value from .env.test
file as shown below:
index.ts402 chars19 lines
In the example above, the dotenv
package is mocked so that it returns the MY_VALUE
variable from .env.test
file. Then, in the beforeEach
block, the dotenv.config()
method is called to load the env variables. Finally, inside the test case, the myFunction
is called and its result is tested against the expected value.
Note: Make sure that the dotenv.config()
method is called before the function that uses the env variables is executed. Also, make sure that the .env.test
file is placed in the root directory of the project.
gistlibby LogSnag