【问题标题】:Laravel Lighthouse GraphQL unit tests: "Variable not defined"Laravel Lighthouse GraphQL 单元测试:“变量未定义”
【发布时间】:2020-11-06 01:42:00
【问题描述】:

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

我正在尝试弄清楚如何在 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

感谢您的支持! :)

【问题讨论】:

    标签: php laravel graphql laravel-lighthouse


    【解决方案1】:

    您在 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
            }
        }
    }
    
    

    【讨论】:

    • 谢谢,我搞定了! :) 我真的不记得了,但我认为我之前也尝试过使用查询包装器,但也许我当时在尝试时错过了一些东西。但它现在可以工作真的很好:)。
    猜你喜欢
    • 2020-01-18
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2014-05-11
    • 2020-05-01
    • 1970-01-01
    相关资源
    最近更新 更多