Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading