{"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-end-to-end-tests","title":"创建端到端测试"}],"documentType":"article"},"body":"# 为网页创建端到端测试\n\n副驾驶聊天 可帮助生成端到端测试。\n\n为网页创建端到端测试可能非常耗时且复杂，因为将动态生成 HTML。 副驾驶聊天 可以帮助你为网页创建端到端测试，通过建议必要的代码来与网页进行交互并验证预期结果。\n\n## 示例方案\n\n想象一个 React 应用程序，该应用程序将在网页上显示产品详细信息。 你需要创建端到端测试，以确保正确显示产品详细信息。 你可以让 副驾驶聊天 为你生成这些测试。\n\n```javascript id=product-details\nimport React, { useState, useEffect } from 'react';\nimport PropTypes from 'prop-types';\n\nconst ProductDetails = ({ productId = '1' }) => {\n  const [product, setProduct] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    const fetchProduct = async () => {\n      try {\n        const response = await fetch(`/api/product/${productId}`);\n        if (!response.ok) {\n          throw new Error('Product not found');\n        }\n        const data = await response.json();\n        setProduct(data);\n        setLoading(false);\n      } catch (err) {\n        setError(err.message);\n        setLoading(false);\n      }\n    };\n\n    fetchProduct();\n    return;\n  }, [productId]); // Add productId to dependency array\n\n  if (loading) return <div>Loading...</div>;\n  if (error) return <div>Error: {error}</div>;\n\n  return (\n    <div>\n      {product && (\n        <div>\n          <h2>{product.name}</h2>\n          <p>{product.description}</p>\n          <p>Price: ${product.price}</p>\n        </div>\n      )}\n    </div>\n  );\n};\n\nProductDetails.propTypes = {\n  productId: PropTypes.string\n};\n\nexport default ProductDetails;\n```\n\n## 示例提示\n\n> \\[!NOTE] 此示例使用 Playwright 进行端到端测试，但你可以使用其他框架，如 Selenium 或 Cypress。\n\n```copilot copy prompt ref=product-details\nUsing Playwright, generate an e2e test to ensure the product displays correctly.\n```\n\n如果你有一个现有测试，并希望 Copilot 作为模型使用，你可以使用 `#file: path/to/test-file.js` 提供文件路径，并在提示中包含该信息。\n\n## 示例响应\n\n> \\[!NOTE] 以下响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\nCopilot 会提供一个端到端测试，你可以将其用于你的应用程序。\n\n```typescript\nimport { test, expect } from '@playwright/test';\n\ntest.describe('ProductDetails Component', () => {\n  test.beforeEach(async ({ page }) => {\n    // Set up API mocking\n    await page.route('/api/product/1', async (route) => {\n      await route.fulfill({\n        status: 200,\n        contentType: 'application/json',\n        body: JSON.stringify({\n          name: 'Test Product',\n          description: 'This is a test product',\n          price: 99.99\n        })\n      });\n    });\n\n    // Mock error response for product ID 999\n    await page.route('/api/product/999', async (route) => {\n      await route.fulfill({\n        status: 404,\n        contentType: 'application/json',\n        body: JSON.stringify({ error: 'Product not found' })\n      });\n    });\n  });\n\n  test('displays loading state initially', async ({ page }) => {\n    await page.goto('/product/1');\n    const loadingElement = page.locator('text=Loading...');\n    await expect(loadingElement).toBeVisible();\n  });\n\n  test('displays product details correctly', async ({ page }) => {\n    await page.goto('/product/1');\n\n    // Wait for loading to disappear\n    await expect(page.getByText('Loading...')).toBeHidden();\n\n    // Check all product details\n    await expect(page.locator('h2')).toHaveText('Test Product');\n    await expect(page.locator('text=This is a test product')).toBeVisible();\n    await expect(page.locator('text=Price: $99.99')).toBeVisible();\n  });\n\n  test('displays error message when product not found', async ({ page }) => {\n    await page.goto('/product/999');\n\n    // Wait for loading to disappear\n    await expect(page.getByText('Loading...')).toBeHidden();\n\n    // Check error message\n    await expect(page.locator('text=Error: Product not found')).toBeVisible();\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)"}