I'm trying to understand how Helpers work. I'm doing a set of helpers for Api call assertions and the first test is passing but the second one is saying that the method doesn't exists in TestCase. How could we use those helpers using High Order tests?
// It works
test('all fields can be null updating user info', fn () => assertApiCallOk('PUT', '/api/user'));
// It throws Call to undefined method Tests\TestCase::assertApiCallOk()
test('all fields can be null updating user info 2')->assertApiCallOk('PUT', '/api/user');
And this is the declaration inside Helpers.php
/**
* Asserts that the api call returns an ok response.
*/
function assertApiCallOk(string $verb, string $url = '', array $payload = []): TestResponse
{
return test()->json($verb, $url, $payload)->assertOk();
}
Thanks!
The helpers allow shorthand functions inside your test closures (or short functions). However, higher order tests need to be added using a trait via uses(TraitName::class).
So for this, you could create a trait such as:
trait InteractsWithApi
{
protected function assertApiCallOk(string $verb, string $url = '', array $payload = []): TestResponse
{
return test()->json($verb, $url, $payload)->assertOk();
}
}
// In your test (or "tests/Pest.php")
uses(InteractsWithApi::class);
If you want to globally:
uses(InteractsWithApi::class)->in(__DIR__);
If you want for a specific folder:
uses(InteractsWithApi::class)->in('Folder');
Thanks guys. Working on it!
Most helpful comment
The helpers allow shorthand functions inside your test closures (or short functions). However, higher order tests need to be added using a trait via
uses(TraitName::class).So for this, you could create a trait such as: