我想重新讨论提出的问题 here和 here关于在使用 selenium 的 Nightwatch.js 中测试文件上传。
两个链接都有将文件输入元素的值设置为 url 的推荐解决方案。在我的用例中,我无法让它发挥作用。即使在 nightwatch 之外手动设置 type="file"
输入的值标签,也不会更改 url。我已经在 Chrome、Firefox 和 IE10 上的开发工具中尝试过此操作。
我研究过的另一种解决方案是尝试模拟整个文件上传过程的击键。这将遵循单击文件上传按钮、输入路径并输入 Enter 的路径。这可以通过 .click
和 .key
方法完成。但是,您会失去实际文件上传窗口的焦点,这会延迟击键,直到该窗口关闭。其他开发人员似乎能够使用 java 中的 .findElement
和 .sendKeys
方法直接在 selenium 中修复此解决方案,但我不知道如何在javascript 和 nightwatch 本身。
有什么想法吗?
// My test
module.exports = {
"Standard File Upload" : function (browser) {
browser
.url("http://localhost:3000")
.waitForElementVisible('body', 1000)
.waitForElementVisible('input[type="file"]', 1000)
.setValue('input[type="file"]','http://localhost:3000/testfile.txt')
.click('#submit')
.pause(1000)
.assert.containsText('h3', 'File Uploaded Successfully')
.end();
}
};
// http://localhost:3000/testfile.txt was tested manually in the file upload window and worked successfully
<小时/>
<!-- My input tag -->
<input id="fileUpload" type="file" name="textfile"/>
最佳答案
我的 setValue()
方法实现存在两个单独的问题。
在 nightwatch 命令中使用 --verbose 标签导致我遇到了一个问题 在该过程中它实际上没有找到输入标签
setValue()
,但它是在waitForElementVisible()
期间。 将input[type="file"]
更改为input#fileUpload
解决了这个问题 问题。其次,以下描述路径的方法不起作用......
'textfile.txt'
'http://localhost:3000/testfile.txt'
(如果在文件上传窗口中手动输入,则有效)
有效的是使用require('path').resolve(__dirname + '/testfile.txt')
看看here查看导致修复的讨论。感谢理查德·弗洛西。
工作代码:
module.exports = {
"Standard File Upload" : function (browser) {
browser
.url("http://localhost:3000")
.waitForElementVisible('body', 1000)
.waitForElementVisible('input#fileUpload', 1000)
.pause(1000)
.setValue('input#fileUpload', require('path').resolve(__dirname + '/testfile.txt')) // Works
// .setValue('input#fileUpload', "testfile.txt") // Will not work
// .setValue('input#fileUpload', "http://localhost:3000/testfile.txt") // Will not work
// .setValue('input[type="file"]', require('path').resolve(__dirname + '/testfile.txt')) // Will not work
.click('#submit')
.pause(1000)
.assert.containsText('h3', 'File Uploaded Successfully')
.end();
}
};
关于selenium - Nightwatch.js 中的文件上传测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25919673/