使用 setInputFiles 时如何在 Playwright 测试中关闭文件输入对话框

问题描述 投票:0回答:1

我正在进行剧作家测试,我需要与文件输入对话框进行交互。我正在使用

setInputFiles
函数来设置输入文件,但遇到了弹出文件输入对话框的问题,而且我似乎无法将其关闭。这导致我的测试挂起,因为对话框保持打开状态。

这是我的测试代码的相关部分:

await page.getByTestId('upload-button').click();

const filePath= path.join(__dirname, "rootPath", "secPath", "package.nupkg");
await page.browseInputField.isVisible();
await page.browseInputField.setInputFiles(filePath);

当执行此行时,我看到文件输入对话框出现,但没有明确的方法来关闭它。 DOM 仅包含一行文件输入元素:

<input id="browseFileInput" data-testid="browseFileInput" class="browseFileInput" type="file" accept=".nupkg">

我没有可以交互的其他按钮或元素来关闭对话框。

我正在寻找一种解决方案,允许我在不弹出对话框的情况下设置输入文件,或者如果确实弹出对话框,则提供一种以编程方式关闭它的方法,以便测试可以继续。

**最小可重复示例** 请创建一个名为

test_page.html
的文件,其中包含以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Page for File Input</title>
</head>
<body>
    <input id="browseFileInput" data-testid="browseFileInput" class="browseFileInput" type="file" accept=".nupkg">
    <button id="upload-button" data-testid="upload-button">Upload</button>

    <script>
        document.getElementById('upload-button').addEventListener('click', function() {
            document.getElementById('browseFileInput').click();
        });
    </script>
</body>
</html>

以及演示该问题的 Playwright 测试脚本:

const { chromium } = require('playwright');
const path = require('path');

(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('file:///path/to/test_page.html');

    await page.click('[data-testid="upload-button"]');

    const filePath = path.join(__dirname, "rootPath", "secPath", "package.nupkg");
    await page.setInputFiles('[data-testid="browseFileInput"]', filePath);

    // Here comes the question - how I close the opened browse dialog?
})();
input file-io playwright e2e-testing dismiss
1个回答
0
投票

我也遇到了这个问题,我决定不使用“setInputFiles”方法。

我建议这样做:

const uploadFile = path.resolve(
      __dirname,
      '../yourPathToTheFile'
    )

const uploadPromise = page.waitForEvent('filechooser')
await page.click('[data-testid="upload-button"]')
const fileChooser = await uploadPromise
await fileChooser.setFiles(uploadFile)

如果您使用调试,您将看到文件选择器弹出窗口不可见。

© www.soinside.com 2019 - 2024. All rights reserved.