If you remember from Chapter 12, JavaScript and Ajax API, we added to our Hello World salutation component a little time widget that displays the current hour in real time if the salutation is not overridden. This component is powered by JavaScript, and more importantly, appended to the page using JavaScript.
Moreover, in the previous section, we wrote a Functional test for the Hello World page in which we asserted the presence of the salutation message. However, the actual time widget would never show up there because the Mink driver used in these types of tests do not support JavaScript. So if we want to test that, we need to write a FunctionalJavascript test.
As expected, these types of tests follow the same patterns for the directory placement and namespaces. So our first test class can start like this:
namespace Drupal\Tests\hello_world\FunctionalJavascript; use Drupal\FunctionalJavascriptTests\WebDriverTestBase; /** * Testing the simple Javascript timer on the Hello World page. * * @group hello_world */ class TimeTest extends WebDriverTestBase {}
By now most of the above code should be clear. However, the base class we extend this time is the WebDriverTestBase class, which itself is a child of BrowserTestBase. Interestingly, it doesn't actually add much to the mix apart from configuring the test to use Selenium Web Driver and adding a few JavaScript specific helper methods. This is to demonstrate that most of the difference between Functional and FunctionalJavascript tests is given by the actual Mink driver.
One extremely handy addition, though, is the ability to take screenshots. Many times when testing frontend interactions, things don't go as we thought and we don't understand why. The parent createScreenshot() method allows us to save a full page screenshot at any given moment, that we can investigate for debugging purposes. All we have to do is pass in the name of the file we want to be saved. So do check that out.
Moving on with our test, let's add the modules we want to be enabled:
/** * Modules to enable. * * @var array */ protected static $modules = ['hello_world'];
As expected, the Hello World module is enough. And the very simple test method can look like this:
/** * Tests the time component. */ public function testTime() { $this->drupalGet('/hello'); $this->assertSession()->pageTextContains('The time is'); $config = $this->config('hello_world.custom_salutation'); $config->set('salutation', 'Testing salutation'); $config->save(); $this->drupalGet('/hello'); $this->assertSession()->pageTextNotContains('The time is'); }
We are using the exact same assertion techniques as before, but because JavaScript is enabled, the time widget text should show up now. And like before, we also test that if the salutation method is overridden, the time widget does not show up.