function AjaxResponseTest::testCommands

Same name and namespace in other branches
  1. 9 core/tests/Drupal/Tests/Core/Ajax/AjaxResponseTest.php \Drupal\Tests\Core\Ajax\AjaxResponseTest::testCommands()
  2. 10 core/tests/Drupal/Tests/Core/Ajax/AjaxResponseTest.php \Drupal\Tests\Core\Ajax\AjaxResponseTest::testCommands()
  3. 11.x core/tests/Drupal/Tests/Core/Ajax/AjaxResponseTest.php \Drupal\Tests\Core\Ajax\AjaxResponseTest::testCommands()

Tests the add and getCommands method.

See also

\Drupal\Core\Ajax\AjaxResponse::addCommand()

\Drupal\Core\Ajax\AjaxResponse::getCommands()

File

core/tests/Drupal/Tests/Core/Ajax/AjaxResponseTest.php, line 35

Class

AjaxResponseTest
@coversDefaultClass <a href="/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21AjaxResponse.php/class/AjaxResponse/8.9.x" title="JSON response object for AJAX requests." class="local">\Drupal\Core\Ajax\AjaxResponse</a> @group Ajax

Namespace

Drupal\Tests\Core\Ajax

Code

public function testCommands() {
    $command_one = $this->createMock('Drupal\\Core\\Ajax\\CommandInterface');
    $command_one->expects($this->once())
        ->method('render')
        ->will($this->returnValue([
        'command' => 'one',
    ]));
    $command_two = $this->createMock('Drupal\\Core\\Ajax\\CommandInterface');
    $command_two->expects($this->once())
        ->method('render')
        ->will($this->returnValue([
        'command' => 'two',
    ]));
    $command_three = $this->createMock('Drupal\\Core\\Ajax\\CommandInterface');
    $command_three->expects($this->once())
        ->method('render')
        ->will($this->returnValue([
        'command' => 'three',
    ]));
    $this->ajaxResponse
        ->addCommand($command_one);
    $this->ajaxResponse
        ->addCommand($command_two);
    $this->ajaxResponse
        ->addCommand($command_three, TRUE);
    // Ensure that the added commands are in the right order.
    $commands =& $this->ajaxResponse
        ->getCommands();
    $this->assertSame([
        'command' => 'one',
    ], $commands[1]);
    $this->assertSame([
        'command' => 'two',
    ], $commands[2]);
    $this->assertSame([
        'command' => 'three',
    ], $commands[0]);
    // Remove one and change one element from commands and ensure the reference
    // worked as expected.
    unset($commands[2]);
    $commands[0]['class'] = 'test-class';
    $commands = $this->ajaxResponse
        ->getCommands();
    $this->assertSame([
        'command' => 'one',
    ], $commands[1]);
    $this->assertFalse(isset($commands[2]));
    $this->assertSame([
        'command' => 'three',
        'class' => 'test-class',
    ], $commands[0]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.