๐ The autostart Flag
๐ The autostart Flag — Designing Testable Async Methods
Async functions are convenient, but they hide execution inside native Promises — which can’t be intercepted or mocked. To preserve control, every asynchronous method in a distributed system should expose a autostart flag.
This simple addition enables you to decide when asynchronous execution actually happens, giving your tests full deterministic control while keeping production behavior untouched.
๐ฏ The Idea
Instead of rewriting async logic for testing, let each function decide whether to execute its asynchronous flow immediately or defer it.
A mockable method:
- Runs normally in production (
autostart = true). - Defers execution in tests (
autostart = false), allowingMockChainto intercept and control outcomes.
⚙️ Implementation Pattern
import { MockChain } from '@fizzwiz/mockchain';
/**
* Fetch data from a URL.
* @param {string} url
* @param {boolean} [mockable=false] - Whether to defer execution for testing.
* @returns {MockChain<Response, Object>}
*/
function doFetch(url, opts, autostart = true) {
const chain = MockChain.fromResponse(url, opts, autostart)
.then(res => res.json());
return chain;
}
The autostart flag directly maps to the MockChain constructor’s autostart parameter. When autostart = true, the internal executor does not run automatically — you take control via .mock() or .fail().
๐งช In Tests
const chain = doFetch(undefined, undefined, true); // mockable mode
chain.root.mock(new Response(JSON.stringify({ ok: true })));
const result = await chain;
console.assert(result.ok === true);
Because execution is deferred, no real network request occurs. You manually trigger the async flow when ready, simulating network latency, failures, or data transformations.
๐ In Production
await doFetch('https://api/data', opts); // default (autostart = true)
In production, the function runs as a standard asynchronous operation. The deferred logic is bypassed, and the fetch request executes normally.
๐งฉ Why This Matters
By introducing an autostart flag:
- Your async functions stay predictable and ergonomic.
- Tests gain deterministic control over every async path.
- You avoid separate testing APIs or code branches.
- It integrates seamlessly with the
MockChain(autostart)design.
Rule: Always give your async methods an
autostartflag. It’s a simple design choice that yields total control, clarity, and confidence in your asynchronous logic.
Comments
Post a Comment