marvinrabe/laravel-graphql-test

为您提供简单的GraphQL测试特性。

0.4.1 2021-08-16 14:51 UTC

This package is auto-updated.

Last update: 2024-08-29 05:00:37 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Laravel的优雅GraphQL测试工具。与任何GraphQL库兼容。特别是与Lighthouse

安装

您可以通过composer安装此包

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

然后将其特性添加到您的TestCase类中

<?php

namespace Tests;

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

    // ...
}

当您的GraphQL端点不是/graphql时,您必须手动指定它

public $graphQLEndpoint = 'graphql';

用法

查询

您可以编写如下查询

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

请注意,此函数返回一个\Illuminate\Foundation\Testing\TestResponse。因此,您可以使用任何Laravel测试方法。例如

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

嵌套资源

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

如果没有第三个参数,则假定第二个参数是选择集

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

当您只传递对象名称时,您将得到GraphQLClient而不是Laravel的TestResponse

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

突变

与查询相同

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

参数顺序

为了简单起见,您可以在以下表中找到正确的参数顺序

枚举

由于PHP没有内置枚举支持,您必须使用提供的枚举辅助器

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

或手动创建一个EnumType

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

头部

您可以通过使用Laravel提供的withHeaderwithHeaders方法来添加额外的HTTP头部。例如

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

如果您始终提供相同的头部,则可以在您的TestCase上定义它们。

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

限制

此库提供的QueryBuilder不适用于生产代码。它设计用于易于使用,并不完全符合GraphQL规范。仅用于测试目的!已警告。

测试

composer test

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。