๐Ÿ 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), allowing MockChain to 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 autostart flag. It’s a simple design choice that yields total control, clarity, and confidence in your asynchronous logic.


Comments

Popular posts from this blog

๐Ÿ”‘ Why MockChain Is a Chain

⚠️ Async Functions Are Not Mockable