syntax error, unexpected 'test' or 'if' when using PestPHP

PestPHP positions itself as "An elegant PHP Testing Framework", but there is one very minor stumbling block you might run into when getting started

Published June 7th 2020

After seeing a lot of posts about Nuno Maduro's new PHP testing wrapper for PHPUnit, Pest PHP, I thought I'd give it a spin. However, after following the installation instructions and getting it running, I ran into an annoying issue; one that didn't appear to be documented.

On writing my first test, I kept running into this error message:

syntax error, unexpected 'test'

As you can imagine, this was more than a little annoying, especially as there was nothing in the (really well written) docs, or in it's Github issues. Had I stumbled on to a new bug? Unlikely, especially at this basic point.

After a little bit of digging, I quickly realised it was my fault (and possibly a lack of caffeine).

The fix

It turns out that I'd made a bit of a boo boo. Rather than delete everything in the file, I'd tried to run the new test function within the class that Laravel had scoped out. Removing everything from the file (including the namespace, includes, and of course, the class itself), and pasting back in the test function got it running.

TL;DR

You're probably trying to run test() within a class. Remove everything but the <?php tag and your test function and it'll work.