---
title: "Resource Optimism"
type: "test-smell"
slug: "resource-optimism"
url: "http://localhost:3000/en/test-smells/resource-optimism.md"
category: "Fixture Smells"
description: "Resource Optimism is when a test assumes an external resource (a file, directory, database table, env var, or network endpoint) already exists and is in a known state instead of provisioning and verifying it, making the test pass or fail non-deterministically."
---
# Resource Optimism

> Resource Optimism is when a test assumes an external resource (a file, directory, database table, env var, or network endpoint) already exists and is in a known state instead of provisioning and verifying it, making the test pass or fail non-deterministically.

## Signs and Symptoms

A test touches something _outside itself_ — a file, temp path, directory, database row, environment variable, or remote endpoint — and simply trusts that it is already there and correctly shaped. There is no setup step that creates the resource and no check that it exists before it is used.

Tell-tale signs:

* A hard-coded path is read or written with no prior `existsSync`/`mkdir`/`writeFile`: e.g. `fs.readFileSync('/tmp/app/config.json')`.
* The test passes on your machine or on the first run, then fails on a clean checkout, on CI, in a different OS temp dir, or when the suite runs in a different order or in parallel.
* The resource it needs is actually created by _another_ test (or a manual/dev-only step), so the test only works as a side effect of run order.
* It opens a file/connection and asserts on the result without ever asserting the resource was present — a missing resource throws before the real assertion, or silently yields empty data that still "passes".

```js
test('parses the config file', () => {
  // optimistic: assumes /tmp/app/config.json already exists and is well-formed
  const raw = fs.readFileSync('/tmp/app/config.json', 'utf8');
  expect(JSON.parse(raw).port).toBe(8080);
});

```

The canonical detection heuristic (testsmells.org / tsDetect): a test uses a `File`\-like resource without first calling an existence/validity check such as `exists()`, `isFile()`, or `notExists()`.

## Reasons for the Problem

**Why it happens**

* The resource was present while the test was written (a fixture file in the repo, a seeded dev database, a temp file left by a prior step), so the author never feels the absence.
* It is simply less code to point at an existing path or table than to allocate and seed one in setup, and to tear it down afterward.
* Copy-paste from another test that already relied on shared, ambient state.

**Why it hurts**

* **Non-determinism / flakiness.** The result depends on the state of the environment, not the code under test. van Deursen et al. describe exactly this: tests that "run fine at one time, and fail miserably at another time." Clean CI runners, fresh checkouts, parallel workers, and different OS temp locations are where it bites.
* **False confidence.** A green test may be passing because of leftover state from a previous run or a previous test, not because the current code is correct — or a missing resource throws early and the meaningful assertion never executes.
* **Hidden coupling and order dependence.** When one test creates what another consumes, the suite has an invisible ordering contract that breaks under shuffling or sharding.
* **Hard to reproduce and maintain.** Failures can't be reproduced locally because they depend on machine-specific ambient state, so debugging is slow and the test erodes trust.

## Treatment

Make each test **own and control** every resource it touches, and never assume ambient state.

1. **Provision in setup, clean up in teardown.** Use _Setup External Resource_ — allocate and initialize files, directories, DB tables, and connections in `beforeEach`/`beforeAll`, and release them in `afterEach`/`afterAll` so the next run starts clean.
2. **Create, don't assume.** Write the file, seed the table, or start the stub server in setup. If you genuinely must consume a pre-existing resource, assert it exists first so a missing resource fails loudly with a clear message instead of corrupting the real assertion.
3. **Isolate per test.** Use a unique temp directory (`fs.mkdtemp(os.tmpdir() + …)`) or a fresh schema/namespace per test rather than a shared hard-coded path, so parallel runs and reruns don't collide.
4. **Better still, remove the dependency.** Replace the real resource with a mock or in-memory fake (mocked `fs`, in-memory DB, stubbed HTTP) so the test is fully self-contained and deterministic — the remediation testsmells.org recommends.

Before → after:

```js
// before — Resource Optimism
test('parses the config file', () => {
  const raw = fs.readFileSync('/tmp/app/config.json', 'utf8');
  expect(JSON.parse(raw).port).toBe(8080);
});

```

```js
// after — test owns and verifies its resource
import { mkdtemp, writeFile, rm, readFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

let dir;
beforeEach(async () => {
  dir = await mkdtemp(path.join(os.tmpdir(), 'cfg-'));
  await writeFile(path.join(dir, 'config.json'), JSON.stringify({ port: 8080 }));
});
afterEach(() => rm(dir, { recursive: true, force: true }));

test('parses the config file', async () => {
  const raw = await readFile(path.join(dir, 'config.json'), 'utf8');
  expect(JSON.parse(raw).port).toBe(8080);
});

```

## Detected by

- **tsDetect** `Resource Optimism` — Resource Optimism (https://testsmells.org/pages/testsmells.html)
