⚡ QuickStart
⚡ QuickStart with @fizzwiz/mockchain
“Test the network one node at a time — by mocking one Promise at a time.”
This QuickStart guide shows you how to use @fizzwiz/mockchain to make asynchronous operations fully mockable — ideal for testing distributed nodes, event-driven systems, or networked applications.
1. Installation
Install via npm:
npm install @fizzwiz/mockchain
Or via yarn:
yarn add @fizzwiz/mockchain
2. Basic Usage
Wrap your Promises in MockChain to make them mockable.
import { MockChain } from '@fizzwiz/mockchain';
// In your code
function doFetch(url, autoStart = true) {
const chain = MockChain.from(fetch(url), autoStart)
.then(res => res.json());
return chain; // returns MockChain<Response, Object>
}
// In your test
const fetchChain = doFetch('https://example.com', false);
fetchChain.root.mock(new Response(JSON.stringify({ ok: true })));
const obj = await fetchChain; // await the result
This simulates a network response without sending a real request.
3. Mocking WebSocket Messages
Simulate WebSocket messages easily:
import { MockChain } from '@fizzwiz/mockchain';
// In code
function sendAndReceive(webSocket, request) {
if (request) webSocket.send(request);
const wsChain = MockChain.fromMessage(webSocket, () => true, false, !!request)
.then(msg => console.log(msg.data));
return wsChain;
}
// In test
const wsChain = sendAndReceive(undefined, undefined);
wsChain.root.mock({ data: 'mocked message' }); // trigger the chain from root
// -> 'mocked message'
4. Mocking Generic Events
Wrap any EventEmitter or EventTarget event in a mockable chain:
import { MockChain } from '@fizzwiz/mockchain';
// In code
function triggerAndReact(trigger, emitter, eventName, isEvent) {
if (trigger) trigger();
const eventChain = MockChain.fromEvent(emitter, eventName, isEvent)
.then(data => console.log(data));
return eventChain;
}
// In test
const eventChain = triggerAndReact(undefined, undefined, () => true);
eventChain.root.mock('mocked event'); // trigger the chain from root
// -> 'mocked event'
5. Delayed Resolution and Rejection
Simulate network latency or delayed events:
const chain = new MockChain(undefined, false).then(console.log);
chain.root.mockAfter(1000, { ok: true }); // resolves after 1 second
const failChain = new MockChain(undefined, false).then(console.log);
failChain.root.failAfter(2000, new Error('Timeout!')); // rejects after 2 seconds
6. Notes & Best Practices
- Only return
MockChainfrom non-async functions to preserve mockability (will be discussed in a dedicated post). - Use
.root.mock()or.root.fail()to control any node in the chain. - Access intermediate nodes via
.parent(previous node) to inspect or mock earlier states. - Pass
autoStart = falseto defer execution until.mock()or.fail()is manually called.
7. Next Steps
- Explore isolating and testing each distributed node using
MockChain. - Combine
MockChainwithfetch,WebSocket, orEventEmittermocks for full control of async logic.
Comments
Post a Comment