如何使用 Selenium/WebdriverIO 探测文件是否已下载

Sal*_*rra 0 javascript node.js selenium-webdriver webdriver-io

我想知道在单击下载按钮后如何验证文件是否是使用 Selenium Webdriver 下载的。

T G*_*ung 5

您的问题没有说明您是想在本地还是远程确认(如 browserstack)。如果是远程的,那么我的答案将是“”,因为您可以看到文件正在下载,但您无法访问该文件夹。因此您将无法断言该文件已被下载。

如果你想在本地(在 Chrome 中)实现这一点,那么答案是“”,你可以这样做:

在 wdio.conf.js 中(了解它的下载位置)

var path = require('path');

const pathToDownload = path.resolve('chromeDownloads');

// chromeDownloads above is the name of the folder in the root directory
exports.config = {
capabilities: [{
        maxInstances: 1,     
        browserName: 'chrome',
        os: 'Windows',      
        chromeOptions: {
            args: [
                'user-data-dir=./chrome/user-data',
            ],
            prefs: {
                "download.default_directory": pathToDownload,
            }
        }
    }],
Run Code Online (Sandbox Code Playgroud)

和你的规范文件(检查文件是否已下载?)

const fsExtra = require('fs-extra');
const pathToChromeDownloads = './chromeDownloads';

describe('User can download and verify a file', () =>{

    before(() => {
        // Clean up the chromeDownloads folder and create a fresh one
        fsExtra.removeSync(pathToChromeDownloads);
        fsExtra.mkdirsSync(pathToChromeDownloads);
    });

    it('Download the file', () =>{
        // Code to download 
    });

    it('Verify the file is downloaded', () =>{
        // Code to verify 
        // Get the name of file and assert it with the expected name
    });
});
Run Code Online (Sandbox Code Playgroud)

有关 fs-extra 的更多信息: https: //www.npmjs.com/package/fs-extra

希望这可以帮助。