View source
<?php
namespace Drupal\Tests\google_analytics\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\search\SearchIndexInterface;
use Drupal\Tests\BrowserTestBase;
class GoogleAnalyticsSearchTest extends BrowserTestBase {
use StringTranslationTrait;
public static $modules = [
'google_analytics',
'search',
'node',
];
protected $adminUser;
protected $defaultTheme = 'stark';
protected function setUp() {
parent::setUp();
$this
->drupalCreateContentType([
'type' => 'page',
'name' => 'Basic page',
]);
$permissions = [
'access administration pages',
'administer google analytics',
'search content',
'create page content',
'edit own page content',
];
$this->adminUser = $this
->drupalCreateUser($permissions);
$this
->drupalLogin($this->adminUser);
}
public function testGoogleAnalyticsSearchTracking() {
$ua_code = 'UA-123456-1';
$this
->config('google_analytics.settings')
->set('account', $ua_code)
->set('privacy.anonymizeip', 0)
->set('track.displayfeatures', 1)
->save();
$this
->drupalGet('');
$this
->assertRaw($ua_code);
$this
->drupalGet('search/node');
$this
->assertNoRaw('gtag("config", ' . Json::encode($ua_code) . ', {"groups":"default","page_path":"');
$this
->config('google_analytics.settings')
->set('track.site_search', 1)
->save();
$search = [
'keys' => $this
->randomMachineName(8),
];
$this
->drupalPostForm('search/node', $search, $this
->t('Search'));
$this
->assertRaw('gtag("config", ' . Json::encode($ua_code) . ', {"groups":"default","page_path":(window.google_analytics_search_results) ?');
$this
->assertRaw('window.google_analytics_search_results = 0;');
$this
->createNodeAndIndex($search['keys']);
$this
->drupalPostForm('search/node', $search, $this
->t('Search'));
$this
->assertSession()
->responseContains('gtag("config", ' . Json::encode($ua_code) . ', {"groups":"default","page_path":(window.google_analytics_search_results) ?');
$this
->assertSession()
->responseContains('window.google_analytics_search_results = 1;');
$this
->createNodeAndIndex($search['keys']);
$this
->drupalPostForm('search/node', $search, $this
->t('Search'));
$this
->assertSession()
->responseContains('gtag("config", ' . Json::encode($ua_code) . ', {"groups":"default","page_path":(window.google_analytics_search_results) ?');
$this
->assertSession()
->responseContains('window.google_analytics_search_results = 2;');
}
protected function createNodeAndIndex($test_string) {
$node = $this
->drupalCreateNode([
'title' => "Someone who says {$test_string}!",
'body' => [
[
'value' => "We are the knights who say {$test_string}!",
],
],
'type' => 'page',
]);
$node_search_plugin = $this->container
->get('plugin.manager.search')
->createInstance('node_search');
$node_search_plugin
->updateIndex();
$search_index = \Drupal::service('search.index');
assert($search_index instanceof SearchIndexInterface);
return $node;
}
}