Skip to content

Testing Patterns ​

waitForTransactionStatus ​

Wait for a transaction to reach a specific status:

ts
import { waitForTransactionStatus } from "statemesh-core/testing";

await waitForTransactionStatus(mesh, "cart.checkout", "success", {
  timeout: 5000
});

waitForMutationStatus ​

ts
import { waitForMutationStatus } from "statemesh-core/testing";

await waitForMutationStatus(mesh, "orders.create", "success", {
  timeout: 5000
});

Test a Transaction ​

ts
it("completes checkout", async () => {
  const mesh = createTestMesh({ state: { cart: { items: [item], status: "idle" } } });

  mesh.transaction("cart.checkout", {
    optimistic(state) { state.cart.status = "processing"; },
    async effect() { return { orderId: "123" }; },
    commit(state, result) {
      state.cart.status = "completed";
      state.order = result;
    }
  });

  await mesh.runTransaction("cart.checkout", undefined);
  mesh.assertStatePath("cart.status", "completed");
  mesh.assertStatePath("order.orderId", "123");
});

Test Error Handling ​

ts
it("handles checkout failure", async () => {
  const mesh = createTestMesh({ state: { cart: { items: [item], status: "idle" } } });

  mesh.transaction("cart.checkout", {
    optimistic(state) { state.cart.status = "processing"; },
    async effect() { throw new Error("Payment declined"); },
    rollback: true
  });

  await expect(mesh.runTransaction("cart.checkout", undefined)).rejects.toThrow();
  mesh.assertStatePath("cart.status", "idle"); // Rolled back
});

Test with Mock Data ​

ts
it("displays products", () => {
  const mesh = createTestMesh({ state: { products: [] } });

  mesh.mockResource("products.list", {
    data: [
      { id: "1", name: "Keyboard", price: 99 },
      { id: "2", name: "Mouse", price: 49 }
    ],
    params: { search: "" }
  });

  const products = mesh.getResourceData("products.list", { search: "" });
  expect(products).toHaveLength(2);
});

Important Notes ​

TIP

Always create a fresh createTestMesh for each test to ensure isolation.

TIP

Use waitForTransactionStatus and waitForMutationStatus for async operations. They poll until the status matches or timeout.

Next Steps ​

Released under the MIT License.