{"meta":{"title":"创建模拟对象来使层抽象化","intro":"Copilot Chat 有助于创建可用于单元测试的模拟对象。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot 指南"},{"href":"/zh/copilot/tutorials/copilot-cookbook/testing-code","title":"测试代码"},{"href":"/zh/copilot/tutorials/copilot-cookbook/testing-code/create-mock-objects","title":"创建模拟对象"}],"documentType":"article"},"body":"# 创建模拟对象来使层抽象化\n\nCopilot Chat 有助于创建可用于单元测试的模拟对象。\n\n创建单元测试时，请务必确保其相互隔离，不依赖于外部服务。 实现这一目标的一种方法是创建模拟对象，以抽象化应用程序的各个层。\nCopilot Chat 可帮助你生成创建这些模拟对象所需的代码。\n\n## 示例方案\n\n假设有一个使用 TypeScript 构建的网站，它显示运行程序列表。 你有一种从数据库提取运行程序的服务，以及使用此服务的服务器端代码。 你想要测试服务器端代码，但不想调用数据库。 可以请求 Copilot Chat 为服务生成模拟对象。\n\n```typescript id=mock-service\n// SvelteKit example at +page.server.ts\nimport service from './service';\n\nexport async function load({ params }) {\n  const runner = await service.getRunner(params.id);\n\n  return {\n    runner\n  };\n}\n```\n\n## 示例提示\n\n此示例假定你使用 [vitest](https://vitest.dev/) 进行测试，但也可使用其他测试运行程序。\n\n```copilot copy prompt ref=mock-service\n/tests Create a unit test to ensure the service is called correctly. Mock the service object.\n```\n\n如果你有要 Copilot 用作模型的现有测试，则可以用于 `#file: path/to/test-file.js` 提供文件的路径，并在提示中包含此信息。\n\n## 示例响应\n\n> \\[!NOTE] 以下响应是示例。 Copilot Chat 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\nCopilot 提供它将实现的计划以及包含模拟的代码文本。\n\n```typescript\nimport { describe, it, expect, vi, beforeEach } from 'vitest';\nimport { load } from './+page.server.ts';\n\n// Mock the entire service module\nvi.mock('./service', () => ({\n  default: {\n    getRunner: vi.fn()\n  }\n}));\n\n// Import the mocked service\nimport service from './service';\n\ndescribe('load function', () => {\n  const mockRunner = {\n    id: '123',\n    name: 'Test Runner',\n    status: 'active'\n  };\n\n  beforeEach(() => {\n    // Reset mock before each test\n    vi.resetAllMocks();\n\n    // Setup default mock implementation\n    (service.getRunner as any).mockResolvedValue(mockRunner);\n  });\n\n  it('should fetch runner with correct id', async () => {\n    const params = { id: '123' };\n    const result = await load({ params });\n\n    expect(service.getRunner).toHaveBeenCalledWith('123');\n    expect(service.getRunner).toHaveBeenCalledTimes(1);\n    expect(result).toEqual({ runner: mockRunner });\n  });\n});\n```\n\n## 延伸阅读\n\n* [GitHub Copilot 对话助手的提示设计](/zh/copilot/concepts/prompting/prompt-engineering)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/get-started/best-practices)"}