You are here

public function FileFieldWidgetTest::testWidgetElement in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/file/tests/src/Functional/FileFieldWidgetTest.php \Drupal\Tests\file\Functional\FileFieldWidgetTest::testWidgetElement()
  2. 9 core/modules/file/tests/src/Functional/FileFieldWidgetTest.php \Drupal\Tests\file\Functional\FileFieldWidgetTest::testWidgetElement()

Tests file widget element.

File

core/modules/file/tests/src/Functional/FileFieldWidgetTest.php, line 393

Class

FileFieldWidgetTest
Tests the file field widget with public and private files.

Namespace

Drupal\Tests\file\Functional

Code

public function testWidgetElement() {
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $html_name = str_replace('_', '-', $field_name);
  $this
    ->createFileField($field_name, 'node', 'article', [
    'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
  ]);
  $file = $this
    ->getTestFile('text');
  $xpath = "//details[@data-drupal-selector='edit-{$html_name}']/table";
  $this
    ->drupalGet('node/add/article');
  $elements = $this
    ->xpath($xpath);

  // If the field has no item, the table should not be visible.
  $this
    ->assertCount(0, $elements);

  // Upload a file.
  $edit['files[' . $field_name . '_0][]'] = $this->container
    ->get('file_system')
    ->realpath($file
    ->getFileUri());
  $this
    ->submitForm($edit, "{$field_name}_0_upload_button");
  $elements = $this
    ->xpath($xpath);

  // If the field has at least one item, the table should be visible.
  $this
    ->assertCount(1, $elements);

  // Test for AJAX error when using progress bar on file field widget.
  $http_client = $this
    ->getHttpClient();
  $key = $this
    ->randomMachineName();
  $post_request = $http_client
    ->request('POST', $this
    ->buildUrl('file/progress/' . $key), [
    'headers' => [
      'Accept' => 'application/json',
      'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    'http_errors' => FALSE,
  ]);
  $this
    ->assertNotEquals(500, $post_request
    ->getStatusCode());
  $body = Json::decode($post_request
    ->getBody());
  $this
    ->assertStringContainsString('Starting upload...', $body['message']);
}