Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

a-dev-coder-f's avatar

How to get intellisense for Pest Test class variables? Ie Adding a Book Service variable

In PHPUnit, I can declare a class variable and initialise it in the setup to use in each subsequent test like below. This has intellisense so when I type $this->bo, I can see my variable $bookService, or when I use $this->bookService-> the intellisense will get the functions inside that variable.

class BookServiceTest extends TestCase
{
    protected BookService $bookService;

    protected function setUp(): void
    {
        parent::setUp();
        $this->bookService = new BookService();
    }

    public function test_get_all_books()
    {
        $books = $this->bookService->getAllBooks();
        $this->assertNotEmpty($books);
    }
}

How can I do the same in Pest PHP?

The equavalent seems to be using beforeEach. However, $this does not have the book service intellisensed because of the cannot load dynamic variables thing.


describe('book service', function () {
   
    beforeEach(function () {
        $this->bookService = new BookService();
    });
    
    it('should get all books', function () {
        $books = $this->bookService->getAllBooks();
    });
});

Using /** @var BookService $this->bookService **/ will not intellisense the bookService variable, but rather the $this variable. Where I want it tied to the variable instead.

My current solution is to declare the class variable at the top of describe, this retains the function intellisense, but now you need to declare the variable in use many many times.

describe('book service', function () {
    $bookService = new BookService();

    it('should get all books', function () use ($bookService) {
        $books = $bookService->getAllBooks();
    });
});
0 likes
1 reply
a-dev-coder-f's avatar

I don't actually know if what I want is even possible, because of how intellisense doesn't read dynamic variables and how Pest takes a closure approach to things.

These are the simple examples, so extrapolate it over time and massively increase the number of tests to get a real scope the situation. Might switch back to PHPUnit instead so it's less of a pain.

Please or to participate in this conversation.