Search code examples
javascriptnode.jstypescriptjestjsdotenv

typescript throws configure not a function error with dotenv and jest


I am trying to use dotenv and jest together, and run into an error immediately.

A single test file, tests/authenticationt.test.ts with only

require('dotenv').configure();

is sufficient to cause this error (it throws this regardless of the presence of tests):

PS C:\Users\rj\code\BGA.ts> npm run test
Debugger attached.

> @ test C:\Users\rj\code\BGA.ts
> jest

Debugger attached.
 FAIL  tests/authentication.test.ts
  ● Test suite failed to run

    TypeError: require(...).configure is not a function

    > 1 | require('dotenv').configure();
        |                               ^
      2 |

      at Object.<anonymous> (tests/authentication.test.ts:1:31)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  modulePaths: [
    "."
  ],
};

package.json

{
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^26.0.23",
    "dotenv": "^10.0.0",
    "jest": "^27.0.4",
    "ts-jest": "^27.0.3",
    "typescript": "^4.3.2"
  },
  "dependencies": {
    "@types/puppeteer": "^5.4.3"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "strictNullChecks": true,
    "outDir": "build",
    "lib": [      
      "es2017",
      "DOM"
    ],
  },
  "include": ["src/**/*"]
}

Additional details

I have not been able to find a stackoverflow question that matches this error; however, this is a basic setup question. This is on a Windows 10 machine, and I'm triggering the tests via powershell. dotenv works fine with my other typescript files (i.e. this is only a problem with jest).


Solution

  • try require('dotenv').config()