4

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

我试图弄清楚如何在 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*
        }
    ]
}].

灯塔是最新版本:4.15.0

谢谢您的支持!:)

4

1 回答 1

2

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

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

如果您使用多个参数,请考虑Input在您的 GraphQL 服务器中创建一个,然后在您的查询中您可以简单地引用您的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
        }
    }
}

于 2020-08-12T16:48:07.140 回答