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:

  1. Compile with checkpointer
  2. Use update_state with as_node to simulate prior state
  3. Invoke with interrupt_after to 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