marvinrabe/laravel-graphql-test

Provides you with a simple GraphQL testing trait.

0.4.1 2021-08-16 14:51 UTC

This package is auto-updated.

Last update: 2024-10-29 05:46:50 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Elegant GraphQL testing utilities for Laravel. Works with any GraphQL library. Especially with Lighthouse.

Installation

You can install the package via composer:

composer require --dev marvinrabe/laravel-graphql-test

And then add the trait to your TestCase class:

<?php

namespace Tests;

abstract class TestCase extends BaseTestCase
{
    use MarvinRabe\LaravelGraphQLTest\TestGraphQL;

    // ...
}

When your GraphQL endpoint is not /graphql you have to specify it manually:

public $graphQLEndpoint = 'graphql';

Usage

Queries

You can write queries like this:

$this->query('account', ['id' => 123], ['id']);

Note that this function returns an \Illuminate\Foundation\Testing\TestResponse. Therefore you might use any Laravel testing methods. For example:

$this->query('account', ['id' => 123], ['id'])
  ->assertSuccessful()
  ->assertJsonFragment([
    'id' => 123
  ]);

With nested resources:

$this->query('account', ['id' => 123], ['transactions' => ['id']]);

Without a third argument it will be assumed that the second one is the selection set:

$this->query('accounts', ['id']);

When you only pass the object name, you get the GraphQLClient instead of the Laravel TestResponse:

$this->query('accounts')->getGql();

Mutations

Same as queries:

$this->mutation('accounts')->getGql();
$this->mutation('accounts', ['id']);
$this->mutation('accounts', ['id' => 123]); 

Argument Order

For simplicity you can find the correct argument order in the following table:

Enums

Because PHP has no built in Enum support. You have to use the provided enum helper:

$this->query('accounts', ['status' => $this->enum('closed')], ['id']);

Or create a EnumType manually:

$this->query('accounts', ['status' => new \MarvinRabe\LaravelGraphQLTest\Scalars\EnumType('closed')], ['id']);

Headers

You can add additional HTTP headers by using withHeader or withHeaders methods provided by Laravel. For example:

$this->withHeaders(["Authorization" => "Bearer TOKEN"])->query('accounts', ['id']);

If you always provide the same headers, you could define them on your TestCase.

class AccountsTest extends TestCase
{
    protected $defaultHeaders = [
        "Authorization" => "Bearer TOKEN",
    ];
    
    // ...
}

Limitations

The QueryBuilder provided by this library is not safe for use in production code. It is designed for ease of use and does not comply to the GraphQL specifications fully. Use it only for testing purposes! You have been warned.

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.