logo

Babylon.js Market

By Lawrence

5 minutes

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 test it. The mesh was built with one seam on purpose, and that seam is what makes it testable. The System never builds its own transport. Instead, it asks a factory for one.

The transport factory you can swap

PokerMultiplayerSystem 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:

src/components/P2PNetwork/P2PNetwork.ts
export interface P2PNetworkSystemOptions {
  /** Override the mesh transport factory (a test double / a custom signaler). */
  connectionFactory?: MeshConnectionFactory;
}

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. It refuses to open a mesh when the browser transport is missing. That is exactly the case under Node.

src/components/P2PNetwork/P2PNetwork.ts
    const injected = this.makeConnection !== createMeshConnection;
    if (!browserHasWebRTC() && !injected) return;

    this.connecting = true;
    this.makeConnection(comp.roomCode, comp.myPlayerId, comp.mySeat, comp.existingPlayers, comp.signalBasePath)

Line 222 holds the whole trick. injected is true when makeConnection is no longer the real createMeshConnection. In other words, it is true when a test passed its own factory. So line 223 says: bail out only if there is no WebRTC and no one injected a factory. A plain Node run has no factory, so it returns early and never throws. A test has a factory, so it slips past the guard and connects to its fake. The rest of connect() then runs the factory just like the browser would.

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search