File uploads not working with PhantomJS

Just a quick one today: when you struggle with writing Acceptance Tests for file uploads using PhantomJS (will version 2.5 ever come out? *sigh*), here are two possible solutions for you.

File inputs are ugly, let’s just not show them

The first issue might be that the input field is hidden for obvious reasons. Luckily we can solve this issue without making your designer cry (and we don’t want to do this, don’t we?) by just tweaking the CSS using JavaScript.

In my case, the input field was hidden by using a very low opacity value, so I set it to 1 just before attaching the actual file:

// PhantomJS 2.1 workaround #1:
// Make input[type=file] visible
$I->executeJS(
   'document.getElementById(\'input-field\').' . 
   'setAttribute(\'style\',\'opacity:1\');'
);
$I->attachFile('#input-field', 'test.jpg');

If this solves your problem – great! If not, I got one more.

Don’t rush – one at a time

While the first issue is somewhat understandable … well, maybe …, anyway, I found the second one just by good old trial-and-error: PhantomJS doesn’t like multiple uploads!

Now we don’t want to remove the possibility to upload multiple files just to please PhantomJS, so let’s do another tweak:

// Phantomjs 2.1 workaround #2:
// Don't use multiple uploads
$I->executeJS(
   'document.getElementById(\'input-field\').' . 
   'removeAttribute(\'multiple\');'
);

Of course we can’t test multiple uploads that way, which is a bit sad, but right now I’m afraid we have to live with that.

Did it blend?

If you found these two little tips helpful, or if you have another nasty PhantomJS workaround at hand, please drop a comment below!

One thought on “File uploads not working with PhantomJS”

Leave a Reply

Your email address will not be published. Required fields are marked *