Created
December 11, 2023 19:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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