PHP code example of newman / laravel-graphql-test-utils

1. Go to this page and download the library: Download newman/laravel-graphql-test-utils library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

newman / laravel-graphql-test-utils example snippets




namespace Tests;

use \Newman\LaravelGraphQLTestUtils\Traits\WithGraphQL;

class SomeTest extends TestCase {
    use WithGraphQL;

    public function test_it_returns_cars(): void
    {
        $response = $this
            ->graphql()
            ->setQuery('query ($search: String!) {
                cars(search: $search) {
                    brand
                }
            }')
            ->setVariables([
                'search' => 'BMW',
            ])
            ->call();
            
        $this->assertEquals([
            'cars' => [
                ['brand' => 'BMW'],
            ],
        ], $response->json('data'));
    }
}



namespace Tests;

use Newman\LaravelGraphQLTestUtils\GraphQLTesting;
use Newman\LaravelGraphQLTestUtils\TestResponse;

class TestCase extends \Illuminate\Foundation\Testing\TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
    
        GraphQlTesting::defaultAssertions(function (TestResponse $response): void {
            $response->assertOk()
                ->assertNoGraphQLErrors();
        });
    }
}

$this
    ->graphql()
    ->setQuery('query {
        cars {
            brand
        }
    }')
    ->call();

$this
    ->graphql()
    ->setVariables(['name' => 'John', 'email' => '[email protected]'])
    ->call();

// Variables will result as: ['name' => 'John', 'email' => '[email protected]']

$this
    ->graphql()
    ->setVariable('name', 'Oliver')
    ->setVariable('surname', 'Smith')
    ->call();

// Variables will result as: ['name' => 'Oliver', 'surname' => 'Smith']

$this
    ->graphql()
    ->setVariables(['name' => 'James', 'email' => '[email protected]'])
    ->setVariable('name', 'Oliver')
    ->setVariable('surname', 'Smith')
    ->mergeVariables(['surname' => 'Williams', 'birthday' => '1990-01-01'])
    ->call();

// Variables will result as: ['name' => 'Oliver', 'email' => '[email protected]', 'surname' => 'Williams', 'birthday' => '1990-01-01']

$this
    ->graphql()
    ->setVariables(['name' => 'John', 'email' => '[email protected]'])
    ->mergeVariables(['name' => 'James'])
    ->call();

// Variables will result as: ['name' => 'James', 'email' => '[email protected]']

$this
    ->graphql()
    ->schema('users')
    ->call();

$this
    ->graphql()
    ->httpMethod('GET')
    ->call();

$this
    ->graphql()
    ->driver('myCustom')
    ->call();

$this
    ->graphql()
    ->withToken('U88Itq0x3yHrhAgCa8mOWuUMKScGAX3zs0xHGnJnvHJoTOmpVTaDX2SVxwxQIsL8')
    ->call();

$this
    ->graphql()
    ->withoutToken()
    ->call();

$this
    ->graphql()
    ->withHeader('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
    ->call();

$this
    ->graphql()
    ->withHeaders([
        'X-User-Language' => 'en',
        'X-Client' => 'GraphQL-Test',
    ])
    ->call();

use \Newman\LaravelGraphQLTestUtils\GraphQLRequest;

$this
    ->graphql()
    ->modifyRequest(function (GraphQLRequest $request) {
        $request->flushHeaders();
        
        // all MakesHttpRequest public methods can be called.
        
        // https://github.com/laravel/framework/blob/9.x/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
    })
    ->call();

$this
    ->graphql()
    ->withoutDefaultAssertions()
    ->call();

function getBaseBuilder() {
    return $this->graphql()->withoutDefaultAssertions();
}

// I want them to be enabled here.
getBaseBuilder()
    ->withDefaultAssertions()
    ->call();

$this
    ->graphql()
    ->call('query ($search: String!) { cars (search: $search) { brand } }', ['search' => 'BMW']);

[
    'name' => ['This field is 

$messages = $response->getValidationFieldMessages('name'); // ['This field is 

$message = $response->getValidationFieldFirstMessage('name'); // 'This field is 



declare(strict_types=1);

namespace App\Support;

use Newman\LaravelGraphQLTestUtils\TestResponse;

class CustomTestResponse extends TestResponse 
{

    public function assertDataAlwaysContainsAge(): static 
    {
        if (!$this->json('data.age')) {
            Assert::fail('Failed to assert that response contains age key.');
        }
    }
}



namespace App\Providers;

use App\Support\CustomTestResponse;
use Newman\LaravelGraphQLTestUtils\GraphQLTesting;

class AppServiceProvider extends \Illuminate\Support\ServiceProvider
{

    public function boot()
    {
        GraphQLTesting::useCustomResponseHandler(CustomTestResponse::class);
    }
}



declare(strict_types=1);

namespace App\Support;

use App\Models\User;
use Newman\LaravelGraphQLTestUtils\GraphQLBuilder;

class CustomGraphQLBuilder extends GraphQLBuilder 
{

    public function withUser(User $user): static 
    {
        $this->withToken($user->api_token)
    
        return $this;
    }
}



namespace App\Providers;

use App\Support\CustomGraphQLBuilder;
use Newman\LaravelGraphQLTestUtils\Contracts\GraphQLBuilderContract;

class AppServiceProvider extends \Illuminate\Support\ServiceProvider
{

    public function register()
    {
        $this->app->bind(GraphQLBuilderContract::class, CustomGraphQLBuilder::class);
    }
}



declare(strict_types=1);

namespace App\Support\GraphQLTestingDrivers;

use Illuminate\Contracts\Config\Repository as ConfigContract;
use Illuminate\Contracts\Container\Container;
use Newman\LaravelGraphQLTestUtils\Contracts\DriverContract;

class MyCustomDriver implements DriverContract
{
    /**
     * @var Container
     */
    protected $app;

    public function __construct(Container $app)
    {
        $this->app = $app;
    }

    public function getUrlPrefix(): ?string
    {
        // ... return your url prefix to GraphQL endpoint. in this case it would be /my-graphql
        // returning null will fallback to default URL prefix.
        return 'my-graphql';
    }

    public function getHttpMethodForSchema(string $schemaName): ?string
    {
        // ... detect HTTP method from schema name and return it.
        // below is an example. You may read it from config or resolve any other way.
        // returning null will fallback to default HTTP method.
        return $schemaName == 'default' ? 'GET' : 'POST';
    }
}



namespace App\Providers;

use App\Support\GraphQLTestingDrivers\MyCustomDriver;
use Newman\LaravelGraphQLTestUtils\GraphQLTesting;

class AppServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function boot()
    {
        // to activate this driver
        
        GraphQlTesting::useDriver('myCustom');
    }
    
    public function register()
    {
        // ... your other bindings
        $this->app->bind('laravel-graphql-utils-driver:myCustom', MyCustomDriver::class);
    }
}