Testing LangGraph Agents
Status: ACTIVE (pulled from docs.langchain.com) Source: https://docs.langchain.com/oss/python/langgraph/test Timestamp: 2026-05-11
Setup
pip install -U pytest
Basic Pattern
Create your graph before each test, compile with a fresh checkpointer:
import pytest
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
def create_graph() -> StateGraph:
class MyState(TypedDict):
my_key: str
graph = StateGraph(MyState)
graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
graph.add_edge(START, "node1")
graph.add_edge("node1", "node2")
graph.add_edge("node2", END)
return graph
def test_basic_agent_execution() -> None:
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
result = compiled_graph.invoke(
{"my_key": "initial_value"},
config={"configurable": {"thread_id": "1"}}
)
assert result["my_key"] == "hello from node2"
Testing Individual Nodes
def test_individual_node_execution() -> None:
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
# Test just node1 in isolation
result = compiled_graph.nodes["node1"].invoke({"my_key": "initial_value"})
assert result["my_key"] == "hello from node1"
Partial Execution (Testing Graph Segments)
Test a specific section without running the entire graph:
- Compile with checkpointer
- Use
update_statewithas_nodeto simulate prior state - Invoke with
interrupt_afterto stop at a specific point
def test_partial_execution() -> None:
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
# Simulate execution up through node1
compiled_graph.update_state(
config={"configurable": {"thread_id": "1"}},
values={"my_key": "initial_value"},
as_node="node1", # State appears as if node1 just completed
)
# Resume from node2, stop after node3
result = compiled_graph.invoke(
None,
config={"configurable": {"thread_id": "1"}},
interrupt_after="node3",
)
assert result["my_key"] == "hello from node3"
Key Testing Patterns
- Fresh checkpointer per test: Prevents state leak between tests
- Test individual nodes:
compiled_graph.nodes["name"].invoke() - Test partial paths:
update_state+as_node+interrupt_after - Test retry logic: Use
retry_policy=RetryPolicy(max_attempts=...)and assert onruntime.execution_info.node_attempt - Extract complex sections as subgraphs: Test subgraphs in isolation