4

I am trying to mock something that imports @env so that I can test different combinations of the values. However, I don't want to change the existing method which reads from the @env to pass in variables.

// env.d.ts
declare module '@env' {
  export const APP_ROUTE_NAME: string;
}

Here's my attempt

import env from '@env';
jest.mock('@env');
describe("Determine initial routes", ()=> {
  it("defaults",()=>{
    // does not work because it is read only
    (env as jest.Mocked<typeof env>).APP_ROUTE_NAME = null
  })
})
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
  • It's to test the logic for what computed values come out depending on the environment variables. – Archimedes Trajano Aug 04 '21 at 00:05
  • Right, but again: that's a solved problem. Use [dotenv](https://www.npmjs.com/package/dotenv) and rely on the fact that it parses values exactly the way it's supposed to? The whole point of a library like this is that it's _rock solid_, you know it works, you don't need to test "env parsing", instead you can focus on testing your own code. – Mike 'Pomax' Kamermans Aug 04 '21 at 00:15
  • you're thinking I am testing the dotenv. I am not I am trying to test my configuration logic. Hence why I am mocking out env. – Archimedes Trajano Aug 04 '21 at 01:48
  • Sort of but no: _why mock anything_? Just have a _separate_ jest.env file for jest, and load that as first call in your test file, and load any number of other files (e.g. from `./testing/environments`) if you need multiple tests for "if specific env vars are different". – Mike 'Pomax' Kamermans Aug 04 '21 at 01:50
  • You didn't provide `@env`, only its types. – Estus Flask Aug 04 '21 at 08:02
  • `@env` is provided by `dotenv` babel. – Archimedes Trajano Aug 04 '21 at 21:20

1 Answers1

1

If you are testing you probably don't need to care about fake secrets being included in your code. So just set the environment variables manually. You could put this is the the a global setup file:

const isDev = process.env.NODE_ENV !== 'production'

module.exports = async () => {
  if (isDev) {
    process.env.API_KEY = 'xxx'
    process.env.OTHER_STUFF = 'xxx'
  }
}
Alex Mckay
  • 3,463
  • 16
  • 27