Skip to content

Test depends on environment: fails on CI but not locally

Quick summary

Your test passes on your machine but fails in CI — it depends on environment-specific settings or resources.

Why this happens

  • The test uses hardcoded file paths that work locally but not in the CI environment

  • Environment variables or configuration that exists locally is missing in CI

  • The test depends on OS-specific behavior, line endings, or file system case sensitivity

Minimal example

✗ Broken code
test('reads config', () => {
  const config = fs.readFileSync('/home/user/config.json'); // works locally, fails in CI
  expect(config.port).toBe(3000);
});
✓ Fixed code
test('reads config', () => {
  const configPath = path.join(process.env.CONFIG_DIR || '/default/config', 'config.json');
  const config = fs.readFileSync(configPath);
  expect(config.port).toBe(3000);
});

Using an environment variable for the config directory makes the test work in both local and CI environments.

How to diagnose

  • Compare the local and CI environments for differences in paths, env vars, and OS

  • Run the test with the same configuration as CI locally (e.g., in a Docker container)

  • Check for hardcoded paths, environment-specific values, or OS-dependent behavior

How to fix

  • Use environment variables or configuration files for environment-specific values

  • Use path.join and path.resolve for file paths instead of hardcoded separators

  • Mock or parameterize OS-specific behavior to make the test environment-independent

How to prevent

  • Never hardcode paths or environment-specific values in tests — use config and env vars

  • Run tests in the same environment as CI (e.g., Docker) to catch environment issues early

Related Resources

Related Glossary

Related Lessons

← Back to language