pestphp / pest

Pest is an elegant PHP testing Framework with a focus on simplicity, meticulously designed to bring back the joy of testing in PHP.
https://pestphp.com
MIT License
9.06k stars 313 forks source link

[2.x] Add PHPStan `$this` annotation (1.11) #1161

Open arondeparon opened 1 month ago

arondeparon commented 1 month ago

What:

Description:

Is it a bug fix? Is it a feature? Quite frankly, I think a bit of both 😁

One of the biggest frustrations for me when using Pest was the fact that the $this keyword is not bound to anything, which causes Phpstan to complain about it like this:

CleanShot 2024-05-23 at 17 05 09

Since PHPStan 1.11.0, there is support for a @param-closure-this annotation that allows us to define what $this means in a Closure.

This MR applies this annotation to the test(), it(), beforeEach() and afterEach() methods, which looks like this:

CleanShot 2024-05-23 at 17 08 31

Caveats

The annotation is currently bound to the PHPUnit\Framework\TestCase object, which is fine in most cases, but if you use a custom TestCase object, this annotation might cause errors such as "phpstan: Call to an undefined method PHPUnit\Framework\TestCase::mock()". I am not sure if there is an easy fix for that, apart from overriding the annotation on a test-level, so I have kept this out of scope for now.