You are here

public function BufferedFieldTest::testBatchedFields in GraphQL 8.4

Same name and namespace in other branches
  1. 8.3 tests/src/Kernel/Framework/BufferedFieldTest.php \Drupal\Tests\graphql\Kernel\Framework\BufferedFieldTest::testBatchedFields()

Test if the schema is created properly.

File

tests/src/Kernel/Framework/BufferedFieldTest.php, line 45

Class

BufferedFieldTest
Test batched field resolving.

Namespace

Drupal\Tests\graphql\Kernel\Framework

Code

public function testBatchedFields() : void {
  $buffer = $this
    ->getMockBuilder(BufferBase::class)
    ->setMethods([
    'resolveBufferArray',
  ])
    ->getMock();
  $users = [
    'a' => [
      'name' => 'A',
      'friends' => [
        'c',
        'd',
      ],
    ],
    'b' => [
      'name' => 'B',
      'foe' => 'e',
    ],
    'c' => [
      'name' => 'C',
    ],
    'd' => [
      'name' => 'D',
    ],
    'e' => [
      'name' => 'E',
    ],
  ];
  $buffer
    ->expects(static::exactly(2))
    ->method('resolveBufferArray')
    ->willReturnCallback(function ($items) use ($users) {
    return array_map(function ($item) use ($users) {
      return $users[$item['uid']];
    }, $items);
  });
  $this
    ->mockResolver('Query', 'users', function ($parent, $args) use ($buffer) {
    $resolvers = array_map(function ($uid) use ($buffer) {
      return $buffer
        ->createBufferResolver(new ArrayObject([
        'uid' => $uid,
      ]));
    }, $args['uids']);
    return new Deferred(function () use ($resolvers) {
      $result = [];
      foreach ($resolvers as $resolver) {
        $result[] = $resolver();
      }
      return $result;
    });
  });
  $this
    ->mockResolver('User', 'name', function ($parent) {
    return $parent['name'];
  });
  $this
    ->mockResolver('User', 'friends', function ($parent) use ($buffer) {
    $resolvers = array_map(function ($uid) use ($buffer) {
      return $buffer
        ->createBufferResolver(new ArrayObject([
        'uid' => $uid,
      ]));
    }, $parent['friends']);
    return new Deferred(function () use ($resolvers) {
      return array_map(function ($resolver) {
        return $resolver();
      }, $resolvers);
    });
  });
  $this
    ->mockResolver('User', 'foe', function ($parent) use ($buffer) {
    $resolver = $buffer
      ->createBufferResolver(new ArrayObject([
      'uid' => $parent['foe'],
    ]));
    return new Deferred(function () use ($resolver) {
      return $resolver();
    });
  });
  $query = $this
    ->getQueryFromFile('batched.gql');
  $metadata = $this
    ->defaultCacheMetaData();
  $this
    ->assertResults($query, [], [
    'a' => [
      [
        'name' => 'A',
        'friends' => [
          [
            'name' => 'C',
          ],
          [
            'name' => 'D',
          ],
        ],
      ],
    ],
    'b' => [
      [
        'name' => 'B',
        'foe' => [
          'name' => 'E',
        ],
      ],
    ],
  ], $metadata);
}