Skip to content

[Bug]: pest-plugin-phpstan Undefined variable: $this inside ->with functions #1827

Description

@ayrtonandino

What Happened

When using Pest’s ->with() dataset feature together with beforeEach to initialize $this properties, PHPStan (via pest-plugin-phpstan) incorrectly reports Undefined variable: $this inside the dataset closures.

 ------ ------------------------------------- 
  Line   PhpstanTest.php                      
 ------ ------------------------------------- 
  20     Undefined variable: $this            
         🪪  variable.undefined               
         ✏️  tests/Feature/PhpstanTest.php:20  
  21     Undefined variable: $this            
         🪪  variable.undefined               
         ✏️  tests/Feature/PhpstanTest.php:21  
 ------ -------------------------------------

How to Reproduce

In any Pest test file (e.g. tests/Feature/PhpstanTest.php):

<?php

declare(strict_types=1);

use function Pest\Laravel\postJson;

beforeEach(function (): void {
    $this->data = ['data1', 'data2'];
});

test('search', function (string $searchValue): void {
    postJson('/api/search', ['search' => $searchValue])->assertOk();
})->with([
    'data 1' => fn(): string => $this->data[0],
    'data 2' => fn(): string => $this->data[1],
]);

Run PHPStan analysis:

vendor/bin/phpstan analyze tests/Feature/PhpstanTest.php

Sample Repository

No response

Pest Version

5.0

PHP Version

8.4.16

Operation System

macOS, Windows, Linux

Notes

While this code runs perfectly fine at test runtime (Pest correctly binds $this to the test case context), PHPStan flags $this as Undefined variable

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions