{"meta":{"title":"创建模拟对象来使层抽象化","intro":"副驾驶聊天 可帮助创建模拟对象用于单元测试。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook","title":"GitHub Copilot Chat 指南"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/testing-code","title":"测试代码"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/testing-code/create-mock-objects","title":"创建模拟对象"}],"documentType":"article"},"body":"# 创建模拟对象来使层抽象化\n\n副驾驶聊天 可帮助创建模拟对象用于单元测试。\n\n创建单元测试时，请务必确保其相互隔离，不依赖于外部服务。 实现这一目标的一种方法是创建模拟对象，以抽象化应用程序的各个层。 副驾驶聊天 可帮助你生成所需的代码来创建这些模拟对象。\n\n## 示例方案\n\n假设有一个使用 TypeScript 构建的网站，它显示运行程序列表。 你有一种从数据库提取运行程序的服务，以及使用此服务的服务器端代码。 你想要测试服务器端代码，但不想调用数据库。 可以让 副驾驶聊天 为此服务生成模拟对象。\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] 以下响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\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/using-github-copilot/prompt-engineering-for-github-copilot)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/using-github-copilot/best-practices-for-using-github-copilot)"}