Prompt
How do I manage multiple API environments in one test suite?
Latest observation
Oct 28, 2026
OpenAI APIWeb search: off
A good way to manage multiple API environments in one test suite is to make environment selection external to the tests and keep the tests themselves environment-agnostic.
Common approach
1. Define environments in config
Store base URLs, credentials, and any environment-specific settings in a config file or environment variables.
Example:
const environments = {
dev: {
baseUrl: 'https://dev.api.example.com',
apiKey: process.env.DEV_API_KEY
},
staging: {
baseUrl: 'https://staging.api.example.com',
apiKey: process.env.STAGING_API_KEY
},
prod: {
baseUrl: 'https://api.example.com',
apiKey: process.env.PROD_API_KEY
}
};
2. Select environment at runtime
Use a command-line flag or environment variable to choose which environment to run against.
Example:
ENV=staging npm test
Then in code:
const envName = process.env.ENV || 'dev';
const config = environments[envName];
3. Keep tests reusable
Write tests that use the selected config rather than hardcoding URLs.
test('GET /users returns 200', async () => {
const res = await fetch(`${config.baseUrl}/users`, {
headers: { Authorization: `Bearer ${config.apiKey}` }
});
expect(res.status).toBe(200);
});
Best practices
- Use environment variables for secrets instead of committing them.
- Avoid hardcoding endpoints in tests.
- Tag or group tests if some should only run in certain environments.
- Create a shared client/helper so all tests use the same environment config.
- Validate config at startup so missing env vars fail fast.
- Separate destructive tests from read-only tests, especially for production.
If you want to run the same suite across all environments
You can run the suite multiple times, once per environment:
ENV=dev npm test
ENV=staging npm test
ENV=prod npm test
Or in CI, create a matrix:
strategy:
matrix:
env: [dev, staging, prod]
Example structure
tests/
api/
users.test.js
src/
config/
environments.js
client/
apiClient.js
If you tell me your test framework (pytest, Jest, Cypress, Postman/Newman, etc.), I can show a concrete setup for it.