pest icon indicating copy to clipboard operation
pest copied to clipboard

To avoid Larastan errors : `test()` is it a correct replacement to `$this` ?

Open girardotcl opened this issue 1 year ago • 2 comments

🧑‍🏭 Context

I have security and code quality needs, i can't simply avoid errors with an ignore line in phpstan.neon like this :

    ignoreErrors:
        -
            message: '#Undefined variable: \$this#'
            path: */Modules/*/Tests/Feature/*
        -
            message: '#Call to an undefined method#'
            path: */Modules/*/Tests/Feature/*

I find the way by replacing all $this with test() :

  • Before, with Larastan error

beforeEach(fn() => $this->category = Category::factory()->create());

test('users can access categories edit route', function (User $user) {
    actingAs($user)
        ->get(route('admin.category.edit', ['category' => $this->category->id]))
        ->assertOk();
})
->with('my user dataset');

// ... other tests
  • After, without larastan error

beforeEach(fn() => test()->category = Category::factory()->create());

test('users can access categories edit route', function (User $user) {
    actingAs($user)
        ->get(route('admin.category.edit', ['category' => test()->category->id]))
        ->assertOk();
})
->with('my user dataset');

// ... other tests

I made some dd() and check the content, it seems ok.

❓Question

But before review all my test suite, I need a confirmation :

⚠️ Is this a solid and sustainable solution from this package point of view ? ⚠️


Pest Version

2.8.1

PHP Version

8.2.13

Operation System

Windows & MacOS

girardotcl avatar Feb 28 '24 09:02 girardotcl

I'm not Pest expert, but looking at Pest internals, more convinent way to get a current test case instance would be:

$test = TestSuite::getInstance()->test;

If you need this to be typed for PHPStan, you can go with assertion that will make PHPStan narrow $test type if you use phpstan-phpunit extension:

assert($test instanceof TestCase); // class of test case you expect to have

rutek avatar Mar 08 '24 08:03 rutek

Thanks for your advice @rutek , I'll make some improvements.

May I still hope an "official" answer ?

girardotcl avatar Mar 25 '24 09:03 girardotcl