5 minutes
Testing a Mesh With No Network
Last lesson, two browser tabs opened a real DataChannel. Peer seats appeared, and net.connected fired on the bus. Then you ran npx vitest run, and Node had never heard of RTCPeerConnection. So does the whole mesh only work when a person opens two browser windows? Can a test ever check it?
You can. The mesh was built with one seam on purpose: the System never builds its own transport, it asks a factory for one.
The transport factory you can swap
P2PNetworkSystem never calls new RTCPeerConnection anywhere. It holds a makeConnection factory instead. One option lets a caller swap that factory out.
The System's options interface:
By default, the constructor uses the real createMeshConnection. The code is this.makeConnection = options?.connectionFactory ?? createMeshConnection. In a browser, nothing changes. In a test, you hand it a different function.
There is one snag: connect() guards itself, refusing to open a mesh when the browser transport is missing — exactly the case under Node.
On line 222, injected is true when makeConnection is no longer the real createMeshConnection — that is, when a test passed its own factory. So line 223 says: bail out only if there is no WebRTC and nobody injected a factory. A plain Node run has no factory, so it returns early and never throws; a test has one, so it slips past the guard and connects to its fake, and the rest of connect() runs the factory exactly as the browser would.
Continue reading
Unlock the Full Course
Every lesson, the runnable examples, and the finished build — yours to keep.