When I started monse.app, my last project, I decided to make all tests with pestphp.com and now, three months later, I can say it was a good decision.
Anyway, this post it's not about if it's a good testing framework or not, it's about some things I learn and makes my tests more readable and simple.
1. Adding helper functions
If you make a lot of tests you will see that you are going to need the same things over and over. To avoid duplicating code and also make the tests more readable a good practice it's to make helper functions.
You can add these functions in the tests/Pest.php
file.
One that I use a lot it's the next one that helps me to get the current test class instance.
function t(): ?TestCase
{
return TestSuite::getInstance()->test;
}
2. Creating factories functions
When you use Laravel factories the IDE doesn't know the class model that it's returning from there and we lose autocomplete and other intentions.
We can do something like these, every time that we are creating a new model:
/** @var User */
$user = User::factory()->create($data);
But I find it more useful and readable to create a new helper function with a typed return.
function user(array $data = []): User
{
return User::factory()->create($data);
}
3. You don't need closures
Usually, when we write a test we do something like:
test('authentication when user is not created', function () {
postJson('/api/login', getTestData())->assertCreated();
});
But with pest actually, you don't need to pass a closure if you don't need and you can write the same test just like this.
test('authentication when user is not created')
->postJson('/api/login', user())
->assertCreated();
Top comments (0)