Laravel Lighthouse GraphQL 单元测试:"Variable not defined"

Laravel Lighthouse GraphQL unit tests: "Variable not defined"

我知道我的问题标题可能不是最有用的,所以如果我能以某种方式改进它,请告诉我:)。

我正在尝试弄清楚如何在 PHP 单元测试中传递 GraphQL 变量,而无需在查询中内联写入它们。

这是一个演示代码。我无法提供确切的真实源代码,因为它属于客户项目。希望这个简化版能说明问题。

class MyGraphQLTest extends Illuminate\Foundation\Testing\TestCase
{
    use Tests\CreatesApplication;
    use \Nuwave\Lighthouse\Testing\MakesGraphQLRequests;

    public function testSomething()
    {
        // Query an article with a specific id defined in this variable
        $this->graphQL(/** @lang GraphQL */ '
                {
                    article(id: $test_id) {
                        id,
                        name
                    }
                }',
            [
                'test_id' => 5, // Does not work, the variable is not passed for some strange reason.
            ]
        )->assertJson([
            'data' => [
                'article' => [ // We should receive an article with id 5 and title 'Test Article'
                    'id' => 5,
                    'name' => 'Test Article',
                ]
            ]
        ]);
    }
}

根据此 Lighthouse: Testing with PHPUnit 指南,变量应该能够作为数组作为第二个参数传递给 ->graphQL() 方法。

当我 运行 使用 php vendor/bin/phpunit 进行测试时,我收到以下错误响应:

[{
    "errors": [
        {
            "message": "Variable \"$test_id\" is not defined.",
            "extensions": {
                "category": "graphql"
            },
            "locations": *removed as not needed in this question*
        }
    ]
}].

Lighthouse 最新版本:4.15.0

感谢您的支持! :)

您在 GraphQL 查询中忘记了某些内容。您必须有一个查询包装器,它将接收参数,然后将定义的变量传递给您的查询。像这样:

query Articles($test_id: Int! /* or ID! if you prefer */){
    {
        article(id: $test_id) {
            id,
            name
        }
    }
}

如果您使用多个参数,请考虑在您的 GraphQL 服务器中创建一个 Input,然后在您的查询中您可以简单地引用您的 Input.

// Consider following Input in your server
input ArticleSearch {
    article_category: String!
    article_rate: Int!
}

// you can then
query Articles($input: ArticleSearch){
    {
        article(input: $input) {
            id,
            name
        }
    }
}