使用 Playwright 进行自动化测试 每天都在流行,并且有许多工具可以帮助您成为其中的高手。有时最难的部分是选择正确的部分。 自动化测试 是一个非常受欢迎的工具,因为它的灵活性和易用性,尤其是在 JavaScript 中。 Playwright 被认为是运行 UI 测试最快的人之一。在本文中,我们将通过代码示例讨论使用 使用 Playwright 编写您的第一个测试的过程。 Playwright JavaScript 安装剧作家 在我们开始编写第一个测试用例之前,您需要安装 Playwright。您可以通过在 IDE 内的终端中运行以下命令来执行此操作。我还建议安装 (它是免费的,非常适合创建您的第一个测试) VScode npm install playwright 编写我们的第一个测试🍾 测试用例 启动 google.com 搜索编剧 搜索后在标题中勾选Playwright 关闭浏览器 让我们首先开始编写测试的架构。 const { chromium } = require('playwright'); describe('Google Search Test', () => { let browser; let page; beforeAll(async () => { }); afterAll(async () => { }); it('should return result search in google ', async () => { }); }); 在所有测试之前总是发生一次。在实际测试之前使用它来设置测试要求非常方便。 beforeAll 例如,通过 API 为测试生成数据或初始化您将在测试中使用的变量。 与 beforeAll 的思路相同。 afterAll 它在所有测试之后只发生一次。您可以在运行测试后关闭浏览器或执行一些操作来清理数据。 我们需要这些变量才能与浏览器和稍后的页面一起使用。 let browser; let page; 这是一个测试主体,我们将在其中编写实际测试。 it('should return result search in google ', async () => { }); 让我们在 里面添加打开浏览器 beforeAll beforeAll(async () => { browser = await chromium.launch(); // here you can use any other browser if you want page = await browser.newPage(); await page.goto('https://www.google.com'); }); 在 中,我们启动了 Chrome 并导航到 google.com。 beforeAll 让我们添加一个测试体 it('should return search results', async () => { await page.fill('id=input', 'Automation testing'); // you an search any other text here await page.press('id=input', 'Enter'); await page.waitForNavigation(); const title = await page.title(); expect(title).toContain('Automation testing'); }); 我们的结果⬆️ 我们在页面上找到输入并在那里写剧作家。 是一种通常用于将值输入要测试的输入的方法。 fill await page.fill('id=input', 'Automation testing'); 当我们在此输入中时,我们模拟按 Enter 键。 await page.press('id=input', 'Enter'); 我们等待页面加载。所以我们不会在页面完全加载之前继续测试。 await page.waitForNavigation(); 最后,我们使用 函数来检索搜索结果页面的标题。 title const title = await page.title(); 使用断言,我们检查标题是否包含 Playwright(或我们正在搜索以确认我们重定向到正确页面的另一个字符串) expect(title).toContain('Automation testing'); 让我们在 里面添加关闭浏览器 afterAll afterAll(async () => { await browser.close(); }); 在 中,我们在所有测试后关闭浏览器 afterAll 运行测试 这将运行你所有的测试 npx playwright test 如果你想运行特定的测试文件 npx playwright test your-file.js 当您运行测试时,Playwright 还会生成 HTML 报告,这对于调试非常有用。它将您的测试分解为多个步骤,如果您的测试失败了,您总能看到失败发生的位置并更快地进行调试。 运行它以打开您的报告 npx playwright show-report 本文的主图是由 HackerNoon 的 通过提示“a developer writing code”生成的。 AI Image Generator