Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Created December 11, 2023 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/b85364e2930eade6f831dc8bac3a2e9c to your computer and use it in GitHub Desktop.
Save Sleavely/b85364e2930eade6f831dc8bac3a2e9c to your computer and use it in GitHub Desktop.
Example of API client instance module that can be replaced and refreshed with fake environment variables on the fly during testing
import { expect, test } from 'vitest'
import myModule from './testable-env-instance'
test('defaults to env', () => {
expect(myModule.token).toBe('INITIAL_TEST_VALUE')
})
test('env can be changed ondemand', () => {
expect(myModule.token).toBe('INITIAL_TEST_VALUE')
myModule._env.POSTMARK_API_TOKEN = 'hello'
expect(myModule.token).toBe('hello')
})
const {
POSTMARK_API_TOKEN = 'INITIAL_TEST_VALUE',
} = process.env
class DummyClass {
token = ''
constructor(token: string) {
this.token = token
}
}
// initial client uses environment variable
let _instance = new DummyClass(POSTMARK_API_TOKEN)
// intercept `_instance._env.POSTMARK_API_TOKEN` prop, for testability
const proxy = new Proxy({}, {
get(target, getProp, receiver) {
if (getProp === '_env') {
return new Proxy({}, {
set(obj, setProp, value) {
if (setProp === 'POSTMARK_API_TOKEN') {
// refresh the client with our new "environment variable"
_instance = new DummyClass(value)
return true
}
return true
}
})
}
// for anything other than ._env, behave like the real client
return Reflect.get(_instance, getProp)
},
}) as DummyClass & { _env: Record<string, string> }
export default proxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment