简体   繁体   中英

How can I upload the file using PHP and Facebook WebDriver?

I am using PHP and Behat (no mink) with Selenium using Facebook WebDriver. I am working on my last test case which is to upload a local file (image) saved on my computer (using a Mac). How can I upload the file using PHP and Facebook WebDriver?

I get the element of the "upload" button and then the pop up comes to choose the file.

$this>webDriver>setFileDetector(new\Facebook\WebDriver\Remote\LocalFileDetector());

// upload the file and submit the form
$this>webDriver>getKeyboard()>sendKeys("/Users/Guest/Documents/image.jpg/;

But this is not working.

I also get this error :

Fatal error: Uncaught Error: Call to undefined method Facebook\\WebDriver\\Remote\\RemoteWebDriver::setFileDetector() in /Users/Guest/Documents/features/bootstrap/FeatureContext.php:232

Consider the following html element.

<input type="file" id="file_input"></input>

Your upload code will look like this:

<?php    
use Facebook\WebDriver\Remote\LocalFileDetector;

//getting the input element
$fileInput = $driver->findElement(WebDriverBy::id('file_input'));

//set the fileDetector
$fileInput->setFileDetector(new LocalFileDetector());

$filePath = 'D:\\work\\udhav.pdf';
$fileInput->sendKeys($filePath);

setFileDetector is a method on the RemoteWebElement class, not the RemoteWebDriver class. You must find the element and then call setFileDetector() on it. See this example:

Source: https://github.com/facebook/php-webdriver/wiki/Upload-a-file

  // getting the input element
  $fileInput = $driver->findElement(WebDriverBy::id('file_input'));
  // set the file detector
  $fileInput->setFileDetector(new LocalFileDetector());
  // upload the file and submit the form
  $fileInput->sendKeys($filePath)->submit();

A note: the line "$fileInput->sendKeys($filePath)->submit();"didn't work for me and was causing errors. I removed the "submit" function call and got this to work: "$fileInput->sendKeys($filePath);". After this line, you'll want to find the form submit button and click it like you would any other form. This sendKeys call takes the place of clicking the browse button and selecting a file to upload. If you take a screenshot after this function call, you can see the selected file's name next to the "Browse..." button just like you would in a manual test of the form.

Link to documentation about the method: https://facebook.github.io/php-webdriver/community/Facebook/WebDriver/Remote/RemoteWebElement.html#method_setFileDetector

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM