简体   繁体   中英

How to unit test GraphQL responses on Lumen?

I'm trying to test an API I built with Lumen (PHP) , but I'm stuck on unit test my GraphQL responses`.

This is what I have tried:

class MovieQueryTest extends Tests\GraphQLTestCase
{
    use DatabaseMigrations;

    public function testCanSearch()
    {
        Movie::create([
            'name' => 'Fast & Furious 8',
            'alias' => 'Fast and Furious 8',
            'year' => 2016
        ]);

        $response = $this->post('/graphql/v1', [
            'query' => '{movies(search: "Fast & Furious"){data{name}}}'
        ]);

        $response->seeJson([
            'data' => [
                'movies' => [
                    'data' => [
                        'name' => 'Fast & Furious 8'
                    ]
                ]
            ]
        ]);
    }
}

This is what I got:

PHPUnit 7.5.6 by Sebastian Bergmann and contributors.

F..... 6 / 6 (100%)

Time: 690 ms, Memory: 24.00 MB

There was 1 failure:

1) MovieQueryTest::testCanSearch Unable to find JSON fragment ["data":{"movies":{"data":{"name":"Fast & Furious"}}}] within [{"data":{"movies":{"data":[]}}}]. Failed asserting that false is true.

The problem is that my data structure doesn't match the JSON's structure. While my data is inside an Array , the JSON's data is inside an Object and I can't figure out how to make it match:

  • ["data":{"movies":{"data":{"name":"Fast & Furious 8"}}}]
  • [{"data":{"movies":{"data":[{"name":"Fast & Furious 8"}]}}}]

How can I make my data structure match the JSON's data structure or there is a better way to unit test GraphQL responses on Lumen?

You need to wrap 'name' => 'Fast & Furious 8' inside it's own array, for example:

The following:

$array = [
    'data' => [
        'movies' => [
            'data' => [
                ['name' => 'Fast & Furious 8']
            ]
        ]
    ]
];

Should output:

{"data":{"movies":{"data":[{"name":"Fast & Furious 8"}]}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM