> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 测试

> 在您原型设计 LangGraph 智能体后，下一步自然是要添加测试。本指南涵盖了在编写单元测试时可以使用的有用模式。

在您原型设计 LangGraph 智能体后，下一步自然是要添加测试。本指南涵盖了在编写单元测试时可以使用的有用模式。

:::python
请注意，本指南是 LangGraph 特定的，涵盖了具有自定义结构的图的相关场景 - 如果您刚开始接触，可以查看使用 LangChain 的内置 @\[`create_agent`] 的 [Test](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/test.md)。
:::

:::js
请注意，本指南是 LangGraph 特定的，涵盖了具有自定义结构的图的相关场景 - 如果您刚开始接触，可以查看使用 LangChain 的内置 @\[`createAgent`] 的 [Test](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/test.md)。
:::

## 前置条件

:::python
首先，确保已安装 [`pytest`](https://docs.pytest.org/)：

```bash theme={null}
$ pip install -U pytest
```

:::

:::js
首先，确保已安装 [`vitest`](https://vitest.dev/)：

```bash theme={null}
$ npm install -D vitest
```

:::

## 入门

由于许多 LangGraph 智能体依赖于状态，一个有用的模式是在每次使用它之前创建您的图，然后在测试中用一个新的检查点实例编译它。

下面的示例展示了如何使用一个简单的线性图（通过 `node1` 和 `node2` 进程）来演示这一点。每个节点都会更新单个状态键 `my_key`：

:::python

```python theme={null}
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"
```

:::

:::js

```ts theme={null}
import { test, expect } from 'vitest';
import {
  StateGraph,
  StateSchema,
  START,
  END,
  MemorySaver,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', END);
};

test('basic agent execution', async () => {
  const uncompiledGraph = createGraph();
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  const result = await compiledGraph.invoke(
    { my_key: 'initial_value' },
    { configurable: { thread_id: '1' } }
  );
  expect(result.my_key).toBe('hello from node2');
});
```

:::

## 测试单个节点和边

编译后的 LangGraph 智能体会暴露每个单个节点的引用作为 `graph.nodes`。您可以利用这一点来测试智能体中的单个节点。请注意，这将绕过编译图时传递的任何检查点器：

:::python

```python theme={null}
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_individual_node_execution() -> None:
    # Will be ignored in this example
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    # Only invoke node 1
    result = compiled_graph.nodes["node1"].invoke(
        {"my_key": "initial_value"},
    )
    assert result["my_key"] == "hello from node1"
```

:::

:::js

```ts theme={null}
import { test, expect } from 'vitest';
import {
  StateGraph,
  START,
  END,
  MemorySaver,
  StateSchema,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', END);
};

test('individual node execution', async () => {
  const uncompiledGraph = createGraph();
  // Will be ignored in this example
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  // Only invoke node 1
  const result = await compiledGraph.nodes['node1'].invoke(
    { my_key: 'initial_value' },
  );
  expect(result.my_key).toBe('hello from node1');
});
```

:::

## 部分执行

对于由较大图组成的智能体，您可能希望测试智能体中的部分执行路径，而不是端到端地测试整个流程。在某些情况下，将 [这些部分重新结构化为子图](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/use-subgraphs.md) 可能具有语义意义，您可以像平常一样单独调用它们。

然而，如果您不希望更改智能体图的整体结构，可以使用 LangGraph 的持久化机制来模拟智能体在所需部分的开始之前暂停的状态，并在所需部分的结束处再次暂停。步骤如下：

:::python

1. 使用检查点器编译您的智能体（用于测试的内存检查点器 @\[`InMemorySaver`] 足够）。
2. 使用 [`update_state`](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/use-time-travel) 方法调用您的智能体，并将 [`as_node`](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/use-time-travel#从特定节点开始) 参数设置为您要开始测试的节点之前的节点的名称。
3. 使用您用来更新状态的相同 `thread_id` 调用您的智能体，并将 `interrupt_after` 参数设置为您要停止的节点的名称。
   :::
   :::js
4. 使用检查点器编译您的智能体（用于测试的内存检查点器 [`MemorySaver`](https://reference.langchain.com/javascript/langchain-langgraph-checkpoint/MemorySaver) 足够）。
5. 使用 [`update_state`](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/use-time-travel) 方法调用您的智能体，并将 [`asNode`](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/use-time-travel#从特定节点开始) 参数设置为您要开始测试的节点之前的节点的名称。
6. 使用您用来更新状态的相同 `thread_id` 调用您的智能体，并将 `interruptBefore` 参数设置为您要停止的节点的名称。
   :::

这里有一个示例，它只执行线性图中的第二和第三个节点：

:::python

```python theme={null}
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_node("node3", lambda state: {"my_key": "hello from node3"})
    graph.add_node("node4", lambda state: {"my_key": "hello from node4"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", "node3")
    graph.add_edge("node3", "node4")
    graph.add_edge("node4", END)
    return graph

def test_partial_execution_from_node2_to_node3() -> None:
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    compiled_graph.update_state(
        config={
          "configurable": {
            "thread_id": "1"
          }
        },
        # The state passed into node 2 - simulating the state at
        # the end of node 1
        values={"my_key": "initial_value"},
        # Update saved state as if it came from node 1
        # Execution will resume at node 2
        as_node="node1",
    )
    result = compiled_graph.invoke(
        # Resume execution by passing None
        None,
        config={"configurable": {"thread_id": "1"}},
        # Stop after node 3 so that node 4 doesn't run
        interrupt_after="node3",
    )
    assert result["my_key"] == "hello from node3"
```

:::

:::js

```ts theme={null}
import { test, expect } from 'vitest';
import {
  StateGraph,
  StateSchema,
  START,
  END,
  MemorySaver,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addNode('node3', (state) => ({ my_key: 'hello from node3' }))
    .addNode('node4', (state) => ({ my_key: 'hello from node4' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', 'node3')
    .addEdge('node3', 'node4')
    .addEdge('node4', END);
};

test('partial execution from node2 to node3', async () => {
  const uncompiledGraph = createGraph();
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  await compiledGraph.updateState(
    { configurable: { thread_id: '1' } },
    // The state passed into node 2 - simulating the state at
    // the end of node 1
    { my_key: 'initial_value' },
    // Update saved state as if it came from node 1
    // Execution will resume at node 2
    'node1',
  );
  const result = await compiledGraph.invoke(
    // Resume execution by passing None
    null,
    {
      configurable: { thread_id: '1' },
      // Stop after node 3 so that node 4 doesn't run
      interruptAfter: ['node3']
    },
  );
  expect(result.my_key).toBe('hello from node3');
});
```

:::

***

> 官方原文：[src/oss/langgraph/test.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/langgraph/test.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.