By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A graph is easier to test than a hand-written loop because it has seams. You can test a node as a plain function, test a router with plain dicts, test the compiled structure, and test a whole path with deterministic nodes or a fake model. None of those layers needs an API key, a network or a database, so the whole suite runs in CI in seconds.
| Layer | What you call | What you assert |
|---|---|---|
| Node | The function directly with a dict | The partial update it returns, and its validation errors |
| Router | The router with dicts covering each branch | The label for each state, including the fallback |
| Structure | compile() and get_graph() | Node names, boundaries, and that missing edges fail early |
| Path | graph.invoke() with fake nodes or a fake model | State values, message trace, interrupts and loop bounds |
Most graph bugs are not runtime bugs; they are wrong updates and wrong routing. Those are pure functions, so test them without building a graph at all. Then compile the graph once as a fixture and assert on its structure and its bounded loop behaviour.
from typing import Literal, TypedDict
import pytest
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
class AttemptState(TypedDict):
attempts: int
def attempt(state: AttemptState) -> dict:
return {"attempts": state["attempts"] + 1}
def route_after_attempt(state: AttemptState) -> Literal["attempt", "done"]:
return "done" if state["attempts"] >= 2 else "attempt"
@pytest.fixture
def graph():
builder = StateGraph(AttemptState)
builder.add_node("attempt", attempt)
builder.add_edge(START, "attempt")
builder.add_conditional_edges(
"attempt",
route_after_attempt,
{"attempt": "attempt", "done": END},
)
return builder.compile()
def test_node_returns_only_its_update():
assert attempt({"attempts": 0}) == {"attempts": 1}
def test_router_is_pure_and_exhaustive():
assert route_after_attempt({"attempts": 0}) == "attempt"
assert route_after_attempt({"attempts": 2}) == "done"
def test_compiled_graph_has_descriptive_nodes(graph):
assert {"__start__", "attempt", "__end__"} <= set(graph.get_graph().nodes)
def test_loop_is_bounded(graph):
assert graph.invoke({"attempts": 0}) == {"attempts": 2}
def test_runaway_loop_hits_the_recursion_limit():
class LoopState(TypedDict):
steps: int
def step(state: LoopState) -> dict:
return {"steps": state["steps"] + 1}
def always_loop(state: LoopState) -> Literal["step"]:
return "step"
builder = StateGraph(LoopState)
builder.add_node("step", step)
builder.add_edge(START, "step")
builder.add_conditional_edges("step", always_loop, {"step": "step"})
runaway = builder.compile()
with pytest.raises(GraphRecursionError):
runaway.invoke({"steps": 0}, {"recursion_limit": 5})For model-shaped nodes, use the fake-model pattern from Lessons 9 and 10. The test is deterministic because the model's turns are scripted, but everything between them — the graph edges, ToolNode dispatch, the message reducer and tools_condition — is the real runtime. Assert on tool names, arguments and ToolMessage contents, never on the exact prose a live model would produce.
from typing import Annotated, TypedDict
import pytest
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage, ToolCall
from langchain_core.tools import tool
from langgraph.graph import START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
class AgentState(TypedDict):
messages: Annotated[list, add_messages]
@tool
def lookup_order(order_id: str) -> str:
"""Read-only: look up an order's status by id."""
orders = {"4521": "delivered (ceramic mug)"}
if order_id not in orders:
raise ValueError(f"Unknown order: {order_id}")
return orders[order_id]
@pytest.fixture
def graph():
# A fresh iterator per test: an exhausted fake model cannot be reused.
model = GenericFakeChatModel(
messages=iter(
[
AIMessage(
content="",
tool_calls=[
ToolCall(
name="lookup_order",
args={"order_id": "4521"},
id="call_1",
)
],
),
AIMessage(content="Order #4521 was delivered."),
]
)
)
def call_model(state: AgentState) -> dict:
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(AgentState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode([lookup_order]))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)
builder.add_edge("tools", "model")
return builder.compile()
def test_tool_arguments_are_exactly_what_the_model_asked_for(graph):
result = graph.invoke(
{"messages": [HumanMessage("Where is order #4521?")]}
)
ai_turns = [
message
for message in result["messages"]
if isinstance(message, AIMessage) and message.tool_calls
]
assert len(ai_turns) == 1
assert ai_turns[0].tool_calls[0]["name"] == "lookup_order"
assert ai_turns[0].tool_calls[0]["args"] == {"order_id": "4521"}
def test_tool_result_reaches_the_final_answer(graph):
result = graph.invoke(
{"messages": [HumanMessage("Where is order #4521?")]}
)
tool_messages = [message for message in result["messages"] if message.type == "tool"]
assert [message.content for message in tool_messages] == [
"delivered (ceramic mug)"
]
assert "delivered" in result["messages"][-1].textgraph.get_graph().draw_mermaid() and the node list show whether the edge you think exists actually exists.stream_mode='updates' shows each node's update in order, which usually localises the bug to a single node.Key takeaways
Test in layers: nodes and routers as pure functions, structure from get_graph(), paths with fake models.
A deterministic fake model keeps model-shaped graphs in CI with no API key; keep one per test with a fresh iterator.
Assert tool names, arguments, ToolMessage contents and message order instead of model prose.
InvalidUpdateError, GraphRecursionError and an unexpected next each point at a specific graph bug.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.