Senior Drupal Developer
Drupal allows writing tests for installation profiles. A profile can have sample content which is created during installation, like umami in Drupal core. Drupal allows writing tests for modules as well. A module can also have sample content which is created during installation or config import.
Drupal Testing Traits allows writing tests for an already installed site. A site with content types and content. You can write tests for the all the pages in your site in different viewports and test user interactions aka JavaScript tests.
Install Drupal test traits package using composer.
composer require'weitzman/drupal-test-traits'
Add phpunit.xml to your project root. Please change the directory structure according to your project.
Create a custom module or add it to custom profile and copy ExistingSiteBase into tests/src
directory feel free to change the file name, class name and namespace to match your project e.g. namespace can be namespace Drupal\Tests\custom_module\Functional;
To write a test, create a new CustomTest
class, extend it from the base class ExistingSiteBase
and write a test method.
Drupal core provides traits to create content, e.g.
Drupal\Tests\node\Traits\NodeCreationTrait
Drupal\Tests\user\Traits\UserCreationTrait
Drupal\Tests\taxonomy\Functional\TaxonomyTestTrait
Drupal\Tests\media\Traits\MediaTypeCreationTrait
Drupal Testing Traits provide the wrapper for all these traits. If the content is created using these traits it will be automatically deleted after the test run is complete.
Here is an example of how NodeCreationTrait
can be used.
<?php// custom_module/tests/src/Functional/NodeCreationTest.phpnamespaceDrupal\Tests\custom_module\Functional;
useweitzman\DrupalTestTraits\ExistingSiteBase;
/**
* Test the node creation.
*/classNodeCreationTestextendsExistingSiteBase{
publicfunctiontestNodeCreation(){
$node = $this->createNode(['type' => 'article']);
// Assert stuff here.
}
}
More examples can be found at https://gitlab.com/weitzman/drupal-test-traits/tree/master/tests/Entity.
Drupal Testing Traits supports both Selenium and WebDriver based functional javascript testing. weitzman\DrupalTestTraits\ExistingSiteSelenium2DriverTestBase
and weitzman\DrupalTestTraits\ExistingSiteWebDriverTestBase
can be used to write functional JS tests.
A couple of JS tests examples can be found in the library ExampleSelenium2DriverTest.php and ExampleWebDriverTest.php .
Drupal Testing Traits comes with the docker-compose file which is fully tested. It can be copied and used after minor modifications. You can run your test using docker composer locally, TravisCI, CircleCI or GitLabCI.