You are here

public function YouTubeTest::testVideo in YouTube Field 8

Test ID validation and the proper video display of a valid ID.

File

tests/src/Functional/YouTubeTest.php, line 131

Class

YouTubeTest
Tests youtube field widgets and formatters.

Namespace

Drupal\Tests\youtube\Functional

Code

public function testVideo() {
  $field_name = mb_strtolower($this
    ->randomMachineName());

  // Create a field.
  $field_storage = \Drupal::entityTypeManager()
    ->getStorage('field_storage_config')
    ->create([
    'field_name' => $field_name,
    'entity_type' => 'node',
    'translatable' => FALSE,
    'type' => 'youtube',
    'cardinality' => '1',
  ]);
  $field_storage
    ->save();
  $field = \Drupal::entityTypeManager()
    ->getStorage('field_config')
    ->create([
    'field_storage' => $field_storage,
    'bundle' => 'article',
    'title' => DRUPAL_DISABLED,
  ]);
  $field
    ->save();
  \Drupal::entityTypeManager()
    ->getStorage('entity_form_display')
    ->load('node.article.default')
    ->setComponent($field_name, [
    'type' => 'youtube',
    'settings' => [],
  ])
    ->save();
  \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load('node.article.default')
    ->setComponent($field_name, [
    'type' => 'youtube_video',
  ])
    ->save();

  // Display creation form.
  $this
    ->drupalGet('node/add/article');
  $this
    ->assertFieldByName("{$field_name}[0][input]", '', t('Video input field is displayed'));

  // Verify that a valid URL can be submitted.
  $video_id = 'T5y3dJYHb_A';
  $value = 'https://www.youtube.com/watch?v=' . $video_id;
  $embed_value = 'https://www.youtube.com/embed/' . $video_id;
  $edit = [
    "title[0][value]" => 'Test',
    "{$field_name}[0][input]" => $value,
  ];
  $this
    ->drupalPostForm(NULL, $edit, t('Save'));
  $this
    ->assertText(t('Article Test has been created.'));
  $this
    ->assertRaw($embed_value);

  // Verify that the video is displayed.
  $pattern = '<iframe.*src="' . $embed_value;
  $pattern = str_replace('/', '\\/', $pattern);
  $pattern = '/' . $pattern . '/s';
  $this
    ->assertPattern($pattern);

  // Verify that invalid URLs cannot be submitted.
  $this
    ->drupalGet('node/add/article');
  $value = 'not-a-url';
  $edit = [
    "title[0][value]" => 'Test1',
    "{$field_name}[0][input]" => $value,
  ];
  $this
    ->drupalPostForm(NULL, $edit, t('Save'));
  $this
    ->assertText(t('Please provide a valid YouTube URL.'));
}