You are here

public function GoogleAnalyticsSearchTest::testGoogleAnalyticsSearchTracking in Google Analytics 8.2

Same name and namespace in other branches
  1. 8.3 tests/src/Functional/GoogleAnalyticsSearchTest.php \Drupal\Tests\google_analytics\Functional\GoogleAnalyticsSearchTest::testGoogleAnalyticsSearchTracking()
  2. 4.x tests/src/Functional/GoogleAnalyticsSearchTest.php \Drupal\Tests\google_analytics\Functional\GoogleAnalyticsSearchTest::testGoogleAnalyticsSearchTracking()

Tests if search tracking is properly added to the page.

File

tests/src/Functional/GoogleAnalyticsSearchTest.php, line 51

Class

GoogleAnalyticsSearchTest
Test search functionality of Google Analytics module.

Namespace

Drupal\Tests\google_analytics\Functional

Code

public function testGoogleAnalyticsSearchTracking() {
  $ua_code = 'UA-123456-1';
  $this
    ->config('google_analytics.settings')
    ->set('account', $ua_code)
    ->save();

  // Check tracking code visibility.
  $this
    ->drupalGet('');
  $this
    ->assertRaw($ua_code);
  $this
    ->drupalGet('search/node');
  $this
    ->assertNoRaw('ga("set", "page",');

  // Enable site search support.
  $this
    ->config('google_analytics.settings')
    ->set('track.site_search', 1)
    ->save();

  // Search for random string.
  $search = [
    'keys' => $this
      ->randomMachineName(8),
  ];

  // Fire a search, it's expected to get 0 results.
  $this
    ->drupalPostForm('search/node', $search, t('Search'));
  $this
    ->assertSession()
    ->responseContains('ga("set", "page", (window.google_analytics_search_results) ?');
  $this
    ->assertSession()
    ->responseContains('window.google_analytics_search_results = 0;');

  // Create a node and reindex.
  $this
    ->createNodeAndIndex($search['keys']);
  $this
    ->drupalPostForm('search/node', $search, t('Search'));
  $this
    ->assertSession()
    ->responseContains('ga("set", "page", (window.google_analytics_search_results) ?');
  $this
    ->assertSession()
    ->responseContains('window.google_analytics_search_results = 1;');

  // Create a second node with same values and reindex.
  $this
    ->createNodeAndIndex($search['keys']);
  $this
    ->drupalPostForm('search/node', $search, t('Search'));
  $this
    ->assertSession()
    ->responseContains('ga("set", "page", (window.google_analytics_search_results) ?');
  $this
    ->assertSession()
    ->responseContains('window.google_analytics_search_results = 2;');
}