Pest: Using helpers in High Order Tests

Created on 3 Jun 2020  路  3Comments  路  Source: pestphp/pest

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!

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:

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);

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nunomaduro picture nunomaduro  路  7Comments

maurobonfietti picture maurobonfietti  路  5Comments

faustbrian picture faustbrian  路  5Comments

zingimmick picture zingimmick  路  3Comments

JacobBennett picture JacobBennett  路  6Comments