phplaravelunit-testingphp-pest

Is it possible to pass a variable from a beforeEach/beforeAll function to my tests? (Pest php)


Right now I'm rewriting some unit tests to use Pest and noticed every test creates a new user. The tests need the id that creating the user returns. I would like to know if it is possible to put this in the beforeEach function Pest provides so I can access this user id in my tests.

I would like to access $user within my tests, is this at all possible? If so, how? I noticed how in Javascript with Jest (which is similar) you can initialize the variable before the BeforeEach, but this does not work in php it seems.

Help would be appreciated!

beforeEach(function () {
    $user = User::factory()->create();
});

test('Test that it shows finished tasks of company', function () {

// Do something with the user variable

//assertion

});

Solution

  • From the documentation at https://pestphp.com/docs/setup-and-teardown#beforeeach

    As usual, the $this variable in the beforeEach function is bound to the current Test Case object. Therefore, you can share data with both it and test functions.

    beforeEach(function () {
        $this->user = User::factory()->create();
    });
    
    test('Test that it shows finished tasks of company', function () {
    
    // You should have access to the user variable as a property:
    
    dump($this->user);
    
    // assertion
    
    });