Playwright 新手,尝试使用简单的“Hello, World”来测试 REST API。示例测试开箱即用,运行良好。我添加了一个调用 GET 端点的 API 测试,但这总是会导致错误。
错误:apiRequestContext.get:连接ECONNREFUSED 2606:4700:20 :: 681a:93b:443
我的 example.spec.ts 看起来像这样。
import { test, expect } from '@playwright/test';
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});
test('API Get Request', async ({request}) => {
const res = await request.get('https://api.myip.com');
expect(res.status()).toBe(200);
const body = await res.json();
});
有什么想法为什么这不起作用吗?
ECONNREFUSED 不是剧作家特有的错误。无论出于何种原因,api.myip.com 拒绝了您的请求。我在我的系统上尝试了您的代码,并没有问题地得到了响应,因此端点is可通过 Playwright 访问。
我建议检查您的
playwright.config.ts
并确保启用跟踪,重新运行测试,然后使用 npx playwright show-report
加载 HTML 报告并打开跟踪文件。跟踪将为您提供所有网络连接详细信息,就像您使用 devtools 捕获了请求一样。请参阅 https://playwright.dev/docs/trace-viewer-intro 了解更多信息。