Use integration tests util
Write integration tests on deployed resources without worrying about the environment variables.
Installation
# using pnpm
pnpm add --save-dev @swarmion/integration-tests
# using yarn
yarn add --save-dev @swarmion/integration-tests
# using npm
npm install --save-dev @swarmion/integration-tests
Usage
1. Declare a test environment variable
import {
TestEnvVar,
SCOPE_CONTEXT_NAME,
TYPE_PATH_CONTEXT_NAME,
} from '@swarmion/integration-tests';
stack.node.setContext(SCOPE_CONTEXT_NAME, 'myScope'); // Optional
stack.node.setContext(TYPE_PATH_CONTEXT_NAME, './testEnvVars.ts'); // Optional
// ...
// latter in a construct
new TestEnvVar(this, 'API_URL', { value: httpApi.url });
This creates a SSM parameter with the value of httpApi.url
.
The name of SSM parameter is :
/testEnvVar/myScope/API_URL
if the CDK ContextSCOPE_CONTEXT_NAME
is defined tomyScope
/testEnvVar/API_URL
if the CDK ContextSCOPE_CONTEXT_NAME
is not defined.
If the CDK Context TYPE_PATH_CONTEXT_NAME
is defined,
the instantiation of the construct will create or sync the file ./testEnvVars.ts
with the following content:
// This file is automatically generated. Do not edit it manually. cf https://www.swarmion.dev/docs/how-to-guides/use-integration-tests
import { getTestEnvVars } from '@swarmion/integration-tests';
export type TestEnvVarsType = {
API_URL: string;
};
export const TEST_ENV_VARS = getTestEnvVars<TestEnvVarsType>();
2. Load the variable in your test environment
Create a setup file for your test runner.
import { syncTestEnvVars } from '@swarmion/integration-tests';
await syncTestEnvVars({
scope: 'myScope', // Optional
cacheFilePath: './testEnvVarsCache.json', // Optional, default to './testEnvVarsCache.json'
cacheDurationInMs: 1000 * 60, // Optional, default is 1h
});
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
setupFiles: ['./integration-tests.setup.ts'],
},
});
This gets the value of the SSM param /testEnvVar/myScope/API_URL
into process.env.API_URL
in each test processes.
syncTestEnvVars
gets all SSM parameters that begin with /testEnvVar/
or /testEnvVar/myScope/
if the scope is
defined to myScope
.
Then it pushes their values into process.env
.
Subsequent calls to syncTestEnvVars
will use cached values instead of fetching SSM. Cache file and duration can be
configured through cacheFilePath
and cacheDurationInMs
options.
The cache file mustn't be committed, add it to .gitignore
.
3. Use the variable in your test
import { TEST_ENV_VARS } from './testEnvVars';
describe('health check', () => {
it('returns 200', async () => {
const response = await fetch(`${TEST_ENV_VARS.API_URL}/health`);
expect(response.status).toBe(200);
});
});
TestEnvVars
is a typesafe version of process.env
.