You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:06:24