[英]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',
]
]
]);
}
}
根据这个灯塔:使用 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
谢谢您的支持: :)
您在 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.