为基本表单提交创建剧作家测试非常适合提交后结果页面上的单一期望:
test('Create todo', async ({ page }) => {
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Next' }).click();
await expect(page.locator('.todo-summary')).toBeVisible();
});
但是当我开始检查错误时,我找不到针对正面和负面情况的好方法
test('Create todo', async ({ page }) => {
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Next' }).click();
// check for errors
// await page.waitForTimeout(4000);
await expect(page.locator('.alert-error')).not.toBeVisible();
});
当表单在服务器端失败并重新呈现表单并显示警报错误 div 时,测试仍然通过。当我将 waitForTimeout 添加到页面时,测试按预期失败。
expect(locator).not.toBeVisible() 是否应该在有或没有waitForTimeout 的情况下工作?或者我在这里遗漏了一些关键的东西?检查错误 div 的好方法是什么?
在没有看到实际页面的情况下很难做出推荐,但通常是这样的:
剧作家定位器总是等待,因此 95% 的时间时间安排都是无关紧要的(有时需要处理一些特定情况)。
这是我们正在测试的页面:
const div = document.querySelector("div");
document.querySelector("form").addEventListener("submit", event => {
event.preventDefault();
if (document.querySelector("input").value.trim() === "magic word") {
div.innerHTML = '<div class="todo-summary">Success!</div>';
}
else {
div.innerHTML = '<div class="alert-error">Failure!</div>';
}
});
<form>
<label>Magic word<input></label>
<input type="submit">
</form>
<div></div>
请注意,有一些特定的用户输入或状态决定了我们期望成功还是失败。这个很重要;如果没有它,就无法启动应用程序以便我们期望成功状态或失败状态。
现在我们测试一下:
import {expect, test} from "@playwright/test"
const html = `<!DOCTYPE html><html><body>
<form><label>Magic word<input></label><input type="submit"></form><div></div>
<script>
const div = document.querySelector("div");
document.querySelector("form").addEventListener("submit", event => {
event.preventDefault();
if (document.querySelector("input").value.trim() === "magic word") {
div.innerHTML = '<div class="todo-summary">Success!</div>';
}
else {
div.innerHTML = '<div class="alert-error">Failure!</div>';
}
});
</script></body></html>`;
test("Creates todo on valid input", async ({page}) => {
await page.setContent(html);
await page.getByLabel("Magic word").type("magic word");
await page.getByRole("button").click();
await expect(page.getByText("Success")).toBeVisible();
await expect(page.getByText("Failure")).not.toBeVisible();
});
test("Doesn't create todo on invalid input", async ({page}) => {
await page.setContent(html);
await page.getByLabel("Magic word").type("not magic word");
await page.getByRole("button").click();
await expect(page.getByText("Failure")).toBeVisible();
await expect(page.getByText("Success")).not.toBeVisible();
});
请注意,您的实际页面可能涉及导航 - 这不应该改变测试,尽管您除了页面内容之外还可以断言
await expect(page).toHaveURL("some url")
。