Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpunit Graphql Laravel Package

lastdragon-ru/phpunit-graphql

PHPUnit helpers for testing GraphQL in PHP apps. Provides assertions and utilities to execute queries/mutations, validate responses, and compare errors/data structures, aimed at simplifying reliable GraphQL API test coverage.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require --dev lastdragon-ru/phpunit-graphql
    

    Ensure lastdragon-ru/graphql-printer is also installed (required dependency):

    composer require lastdragon-ru/graphql-printer
    
  2. Basic Assertion Example Use the GraphQLAssertions trait in your test class to validate GraphQL queries or schemas:

    use LastDragonRu\PhpUnitGraphQL\GraphQLAssertions;
    
    class GraphQLTest extends TestCase
    {
        use GraphQLAssertions;
    
        public function testQueryMatchesExpected()
        {
            $query = <<<'GRAPHQL'
                query {
                    user(id: 1) {
                        id
                        name
                    }
                }
            GRAPHQL;
    
            $this->assertGraphQLQueryMatches($query, [
                'user' => [
                    'id' => 1,
                    'name' => 'John Doe',
                ],
            ]);
        }
    }
    
  3. Key Methods to Explore First

    • assertGraphQLQueryMatches(): Validate a query against expected output.
    • assertGraphQLSchemaMatches(): Validate a schema against a reference.
    • assertGraphQLDocumentMatches(): Compare two GraphQL documents (queries/fragments).

Implementation Patterns

Workflow: Testing GraphQL Responses

  1. Mock or Execute Queries Use Laravel’s HTTP testing or a GraphQL client (e.g., webonyx/graphql-php) to fetch responses.

    $response = $this->graphQL('query { user(id: 1) { name } }');
    $actual = $response->getData();
    
  2. Assert Structure Combine with GraphQLAssertions to validate structure:

    $this->assertGraphQLQueryMatches($query, $expectedData);
    
  3. Schema Validation Test schema compliance during development:

    $schema = new \GraphQL\Type\Schema([...]);
    $this->assertGraphQLSchemaMatches($schema, $referenceSchema);
    

Integration with Laravel

  • Pest PHP: Works seamlessly with Pest’s fluent assertions.
    expect($query)->graphQL()->toMatch($expected);
    
  • Livewire/Inertia: Test GraphQL mutations triggered by UI actions.
    $this->livewire(UpdateProfile::class)
         ->call('updateName', 'Alice')
         ->assertGraphQLMutationMatches('updateProfile', ['name' => 'Alice']);
    

Testing Fragments

Reuse assertions for fragments:

$fragment = <<<'GRAPHQL'
  fragment UserFields on User {
    id
    name
  }
GRAPHQL;

$this->assertGraphQLDocumentMatches($fragment, $referenceFragment);

Gotchas and Tips

Pitfalls

  1. Schema Mismatches

    • Issue: assertGraphQLSchemaMatches() fails if the schema lacks optional fields.
    • Fix: Use strict: false or mock partial schemas:
      $this->assertGraphQLSchemaMatches($schema, $reference, strict: false);
      
  2. Whitespace Sensitivity

    • GraphQL printers may normalize whitespace. Use trim() or GraphQLPrinter::print() for consistency:
      $this->assertGraphQLDocumentMatches(
          trim($query),
          trim($reference)
      );
      
  3. Dynamic Variables

    • Issue: Queries with variables (e.g., $id: ID!) may fail if not mocked.
    • Fix: Use GraphQLAssertions::withVariables():
      $this->assertGraphQLQueryMatches($query, $expected, ['id' => 1]);
      

Debugging Tips

  • Inspect Raw Outputs Log the actual vs. expected for debugging:
    $this->assertGraphQLQueryMatches($query, $expected, debug: true);
    
  • Partial Matches Use assertGraphQLQueryContains() for loose validation:
    $this->assertGraphQLQueryContains($query, 'user { id }');
    

Extension Points

  1. Custom Printers Override the default printer in config/graphql.php:

    'printer' => \App\CustomGraphQLPrinter::class,
    
  2. Custom Assertions Extend the trait for domain-specific rules:

    use LastDragonRu\PhpUnitGraphQL\GraphQLAssertions;
    
    trait CustomGraphQLAssertions {
        protected function assertGraphQLHasPagination($query) {
            $this->assertGraphQLQueryContains($query, 'pageInfo { ... }');
        }
    }
    
  3. CI Optimization Cache schema references in CI to speed up tests:

    static::boot(function () {
        $schema = require __DIR__.'/schema.cache.php';
        GraphQLAssertions::setReferenceSchema($schema);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen