Playwright+Jest:如何验证元素不存在(Teams文件上传测试)
在Playwright+Jest中验证Teams文件上传前目标文件不存在的实现
要在上传操作前确认button:has-text("example.txt")元素不存在,你需要先进入文件列表页面确保检查上下文正确,再利用Playwright提供的元素状态断言或等待方法实现验证。以下是两种可行方案:
方案一:使用waitFor等待元素脱离DOM
通过waitFor指定state: "detached"(元素完全不在DOM中),确保目标文件未被渲染:
it('should upload a file', async () => { // Listen to file chooser popup and set file for upload page.on('filechooser', async (fileChooser) => { await fileChooser.setFiles('test-files/example.txt'); }); // wait for the content iframe to be loaded const contentFrame = page.frameLocator('[name="embedded-page-container"]'); // 先进入文件列表页面,确保检查上下文正确 await contentFrame.locator('button[name="Files"]').click(); // 等待目标文件元素脱离DOM(确认文件不存在) await contentFrame.locator('button:has-text("example.txt")').waitFor({ state: "detached", timeout: 5000 // 可根据页面加载速度调整超时时间 }); // upload file and check for existence in file list displayed await contentFrame.locator('button[name="Upload"]').click(); await contentFrame.locator('button[name="Files"]').click(); await contentFrame.locator('button:has-text("example.txt")').waitFor({ state: "visible" }); });
方案二:使用Playwright断言API结合Jest
直接用toBeDetached断言验证元素不存在于DOM中:
it('should upload a file', async () => { // Listen to file chooser popup and set file for upload page.on('filechooser', async (fileChooser) => { await fileChooser.setFiles('test-files/example.txt'); }); // wait for the content iframe to be loaded const contentFrame = page.frameLocator('[name="embedded-page-container"]'); // 先进入文件列表页面 await contentFrame.locator('button[name="Files"]').click(); // 断言目标文件元素不存在(脱离DOM) await expect(contentFrame.locator('button:has-text("example.txt")')).toBeDetached(); // upload file and check for existence in file list displayed await contentFrame.locator('button[name="Upload"]').click(); await contentFrame.locator('button[name="Files"]').click(); await contentFrame.locator('button:has-text("example.txt")').waitFor({ state: "visible" }); });
关键说明
- 必须先点击
Files按钮进入文件列表页面,否则元素本身不在当前页面DOM中,检查会失去意义。 - 如果文件不存在时元素仅被隐藏而非完全不渲染,可将
detached替换为hidden,对应断言用toBeHidden()。 - 超时时间可根据网络或页面响应速度调整,避免因等待过短导致误判。
内容的提问来源于stack exchange,提问作者Serban
相关产品推荐
相关产品推荐

