nexus
Testing

Unit Testing With createMockNexus

Unit test Nexus-consuming application code with an injectable mock.

Use createMockNexus() when the code under test accepts or reads a NexusInstance and you want deterministic unit tests without a real Nexus topology.

Install

pnpm add -D @nexus-js/testing

Service-Consuming Modules

Application code can accept a NexusInstance directly:

import type { NexusInstance } from "@nexus-js/core";
import { UserToken } from "./shared";

export async function loadUserName(nexus: NexusInstance, id: string) {
  const connection = await nexus.connect({
    target: { context: "background" },
  });
  const users = connection.get(UserToken);

  return (await users.getUser(id)).name;
}

The unit test registers the service behind the same Token:

import { createMockNexus } from "@nexus-js/testing";
import { UserToken, type UserService } from "./shared";
import { loadUserName } from "./load-user-name";

const mock = createMockNexus();

const users: UserService = {
  async getUser(id) {
    return { id, name: "Ada" };
  },
};

mock.service(UserToken, users);

await expect(loadUserName(mock.nexus, "u1")).resolves.toBe("Ada");

expect(mock.calls.connect()).toHaveLength(1);

React Component Tests

Use NexusProvider directly. The testing package does not add a React subpath or a separate provider abstraction.

import { render } from "@testing-library/react";
import { NexusProvider } from "@nexus-js/react";
import { createMockNexus } from "@nexus-js/testing";

const mock = createMockNexus();
mock.service(UserToken, users);

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <NexusProvider nexus={mock.nexus}>{children}</NexusProvider>
);

render(<UserPanel />, { wrapper });

Testing Connection Boundaries

The mock’s connection seam lets application tests exercise the shape of connection acquisition and service lookup. Use Core or adapter integration tests for connection failures, handshakes, authorization, disconnects, and reconnects; the mock does not simulate those runtime behaviors.

const connection = await mock.nexus.connect({
  target: { context: "background" },
});
const result = connection.safeGet(UserToken);

if (result.isErr()) throw result.error;
await result.value.getUser("u1");

Configuring Services In Tests

mock.nexus.configure({ providers }) records the config and registers providers:

mock.nexus.configure({
  providers: [{ token: UserToken, service: users }],
});

expect(mock.calls.configure()).toHaveLength(1);

mock.service(Token, implementation) is an unscoped registration. Pass provider metadata as the optional third argument when a test needs where filtering during connection acquisition.

The mock stores config.policy for assertions but does not execute canConnect or canCall.

Release And Cleanup Assertions

release and safeRelease apply to remote references, not ordinary service proxies. Test those calls with a remote reference returned by the service under test; dropping a root service proxy does not close its shared connection.

Selection And Multicast

connect({ target, where, timeout, signal }) acquires one ready mock session; without a target it models passive acquisition and never discovers providers. connectMulticast(...) returns a fixed collection whose get(Token) method returns per-connection Results. The mock does not simulate real connection acquisition or provider-catalog negotiation.

For the new connection lifecycle, use Core or adapter integration tests. The mock does not establish real connections, exercise onConnect or subscribeIdentity, or validate collection snapshots.

Use core or adapter integration tests for real acquisition, provider-catalog protocol behavior, where(contextMeta, connectionMeta), and adapter topology.

Clearing State Between Tests

afterEach(() => {
  mock.clear();
});

clear(token) removes that token’s registered service and connection records. clear() removes all registered services, injected failures, connection records, configure records, release records, and update-identity records.

Boundaries

createMockNexus() tests application behavior at the Nexus API seam. It does not validate:

  • endpoint implementation correctness
  • browser postMessage
  • Chrome runtime ports
  • Node socket paths, framing, or auth
  • adapter metadata collection
  • real disconnect or reconnect ordering
  • daemon restart or iframe reload behavior
  • core authorization policy execution
  • transport graphs, dynamic discovery, or adapter connection-metadata evaluation
Edit this page on GitHub