Fix bug where analytics tries to init in tests which don't import it #3185
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi @andysellick,
Would you be able to approve this if all is OK?
Thanks 👍
What
We want the analytics to load in if it hasn't been already, which is why we check for
undefined
values, and load in analytics if the values are undefined.However, our tests do not import
load-analytics.js
by default, so having a nested check likewindow.GOVUK.analyticsGa4.vars
resulted in an error in our tests, aswindow.GOVUK.analyticsGa4
didn't exist, so we couldn't run a check onwindow.GOVUK.analyticsGa4.vars
without the JS crashing.Therefore I have added extra if statements which ensure this code only runs when we can guarantee that
load-analytics.js
has been imported.I've checked this against the Jasmine tests in
frontend
,finder-frontend
, andgovernment-frontend
and they're now passing.Why
Without this, tests across our applications to fail, because the
DOMContentLoaded
code was running on tests which did not haveload-analytics.js
loaded into the DOM (which is imported only when_layout_for_public
is rendered. Sowindow.GOVUK.analyticsGa4
did not exist and then thewindow.GOVUK.analyticsGa4.vars
check would crash.Visual Changes
None.