使用Webdriver.io上传文件时遭遇"invalid argument"错误求助
Webdriver.io v8 文件上传"invalid argument"错误解决方案
针对你在MacBook Pro M1上使用Webdriver.io v8 + TypeScript向input[type=file]上传文件时遇到的"invalid argument"错误,以下是几个可行的排查和解决方法:
1. 确保ChromeDriver与Chrome版本完全匹配
你的Chrome版本是119.0.6045.199,必须使用同版本号的ChromeDriver,且要选择适配Apple Silicon(arm64)的版本:
- 手动下载对应版本的ChromeDriver,选择arm64架构包
- 在Webdriver.io配置中指定ChromeDriver路径,或确保
@wdio/chromedriver-service自动下载的是正确架构的版本
2. 尝试传递数组格式的文件路径
Webdriver.io v8中,针对文件输入框,setValue方法有时需要接收数组格式的路径(即使是单个文件),修改代码如下:
public async uploadFile() { const docPath = path.resolve( __dirname, "../../../../../resources/documents/healthy-homes.pdf", ); await this.fileUploadInput.waitForDisplayed(); await this.fileUploadInput.waitForEnabled(); // 改为数组形式传入路径 await this.fileUploadInput.setValue([docPath]); }
3. 绕过Webdriver API,直接用JS设置元素值
通过browser.execute直接操作DOM设置input的value属性,避免Webdriver的封装限制:
public async uploadFile() { const docPath = path.resolve( __dirname, "../../../../../resources/documents/healthy-homes.pdf", ); await this.fileUploadInput.waitForDisplayed(); await this.fileUploadInput.waitForEnabled(); await browser.execute((element, filePath) => { element.value = filePath; }, await this.fileUploadInput, docPath); }
4. 调整Chrome启动参数
在你的wdio配置文件中,为Chrome添加允许文件访问的启动参数,同时适配M1芯片的沙箱问题:
// wdio.conf.ts export const config: WebdriverIO.Config = { // ...其他配置 capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { args: [ '--allow-file-access-from-files', '--no-sandbox', '--disable-dev-shm-usage' ] } }], // ...其他配置 };
5. 验证元素定位的唯一性
确保你的定位器$("input[name='document']")只匹配到一个元素,避免误操作其他隐藏的同名输入框:
// 添加代码检查元素数量 const inputs = await $$("input[name='document']"); console.log(`找到${inputs.length}个匹配的文件输入框`); // 确保取到的是正确的那个,比如第一个可见的 const targetInput = await inputs.find(async el => await el.isDisplayed()); await targetInput.setValue(docPath);
内容的提问来源于stack exchange,提问作者Reizar
相关产品推荐
相关产品推荐

