Core APIs
These APIs work with sandboxed JavaScript to build custom templates in Google Tag Manager. Each API is added with a require()
statement, e.g.:
const myAPI = require('myAPI');
addEventCallback
The addEventCallback
API allows you to register a callback function that will be invoked at the end of an event. The callback will be invoked when all the tags for the event have executed, or if an in page event timeout is reached. The callback is passed two values, the id of the container that invokes the function and an object that contains information about the event.
Syntax
addEventCallback(callback)
Parameters
Parameter | Type | Description |
---|---|---|
callback |
function | The function to invoke at the end of the event. |
The eventData
object contains the following data:
Key Name | Type | Description |
---|---|---|
tags |
Array | An array of tag data objects. Every tag that fired during the event will have an entry in this array. The tag data object contains the tag's ID (id ), its execution status (status ), and its execution time (executionTime ). The tag data will also include additional tag metadata that was configured on the tag. |
Example
addEventCallback(function(ctid, eventData) {
logToConsole('Tag count for container ' + ctid + ': ' + eventData['tags'].length);
});
Associated permissions
aliasInWindow
The aliasInWindow
API lets you create an alias (e.g. window.foo = window.bar
), which helps to support certain tags that require aliasing. Assigns the value in the window
object found at the fromPath
to the key in the window
object at the toPath
. Returns true
if successful, false
otherwise.
Syntax
aliasInWindow(toPath, fromPath)
Parameters
Parameter | Type | Description |
---|---|---|
toPath |
string | A dot-separated path into the window object where a value should be copied to. All components in the path up to the last component must already exist in the window object. |
fromPath |
string | A dot-separated path into window to the value to copy. If the value does not exist, the operation will fail. |
Example
aliasInWindow('foo.bar', 'baz.qux')
Associated permissions
access_globals
is required for both toPath
and fromPath
; toPath
requires write access, fromPath
requires read access.
callInWindow
Allows you to call functions from a path off the window
object, in a policy-controlled way. Calls the function at the given path in window
with the given arguments and returns the value. If the return type can't be directly mapped to a type supported in sandboxed JavaScript, undefined
will be returned. The eight types supported in sandboxed JavaScript are null
, undefined
, boolean
, number
, string
, Array
, Object
, and function
. If the given path does not exist, or does not reference a function, undefined
will be returned.
Syntax
callInWindow(pathToFunction, argument [, argument2,... argumentN])
Parameters
Parameter | Type | Description |
---|---|---|
pathToFunction |
string | A dot-separated path to the function in window to call. |
args |
* | Arguments to be passed to the function. |
Associated permissions
access_globals
with execute
permission enabled.
callLater
Schedules a call to a function to occur asynchronously. The function will be called after the current code returns. This is equivalent to setTimeout(<function>, 0)
.
Syntax
callLater(function)
Parameters
Parameter | Type | Description |
---|---|---|
function |
function | The function to call. |
copyFromDataLayer
Returns the value currently assigned to the given key in the data layer: The value found at the given key if it's a primitive type, function, or object literal, or undefined
otherwise.
Syntax
copyFromDataLayer(key[, dataLayerVersion])
Parameters
Parameter | Type | Description |
---|---|---|
key |
string | The key in the format of "a.b.c". |
dataLayerVersion |
number | The optional data layer version. The default value is 2. It is strongly discouraged to use the value 1. |
Associated permissions
copyFromWindow
Copies a variable from window
object. If the value in window
can't be directly mapped to a type supported in sandboxed JavaScript, undefined
will be returned. The eight types supported in sandboxed JavaScript are null
, undefined
, boolean
, number
, string
, Array
, Object
, and function
. Returns the fetched (and coerced) value.
Syntax
copyFromWindow(key)
Parameters
Parameter | Type | Description |
---|---|---|
key |
string | The key in the window to copy the value of. |
Associated permissions
createArgumentsQueue
Creates a queue that is populated with argument objects, in support of tag solutions that require it.
Creates a function in global scope (i.e. window
), using the fnKey
argument (same semantics as createQueue
). After the function is created, this API then creates an array in window
(if it doesn't already exist) using the arrayKey
argument.
When the function created under fnKey
is called, it pushes its arguments object onto the array created under arrayKey
. The API's return value is the function created under fnKey
.
This function requires the read and write setting for fnKey
and arrayKey
on the access_globals
permission.
Example:
const gtag = createArgumentsQueue('gtag', 'dataLayer');
gtag('set', {'currency': 'USD'});
Syntax
createArgumentsQueue(fnKey, arrayKey)
Parameters
Parameter | Type | Description |
---|---|---|
fnKey |
string | The path in window where the function is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. That is, if fnKey is 'one.two' , it will throw an exception. |
arrayKey |
string | The path in window where the array is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. That is, if arrayKey is 'one.two' , and there is no global object named 'one' , it will throw an exception. |
Associated permissions
createQueue
Creates an array in window
(if it doesn't already exist) and returns a function that will push values onto that array.
This function requires the read and write setting for arrayKey
on the access_globals
permission.
Example:
const dataLayerPush = createQueue('dataLayer');
dataLayerPush({'currency': 'USD'}, {'event': 'myConversion'});
Syntax
createQueue(arrayKey)
Parameters
Parameter | Type | Description |
---|---|---|
arrayKey |
string | The key in window where the array is set, if it does not already exist. This argument supports standard dot notation. If the key's path does not exist, an exception is thrown. For example, if arrayKey is 'one.two' , and there is no global object named 'one' , it will throw an exception. |
Associated permissions
decodeUri
Decodes any encoded characters in the provided URI. Returns a string that represents the decoded URI. Returns undefined
when provided with invalid input.
Example:
const decode = require('decodeUri');
const decodedUrl = decode(data.encodedUrl);
if (decodedUrl) {
// ...
}
Syntax
decodeUri(encoded_uri)
Parameters
Parameter | Type | Description |
---|---|---|
encoded_uri |
string | A URI that has been encoded by encodeUri() or by other means. |
Associated permissions
None.
decodeUriComponent
Decodes any encoded characters in the provided URI component. Returns a string that represents the decoded URI component. Returns undefined
when provided with invalid input.
Example:
const decode = require('decodeUriComponent');
const decodedUrl = decode(data.encodedUrl);
if (decodedUrl) {
// ...
}
Syntax
decodeUriComponent(encoded_uri_component)
Parameters
Parameter | Type | Description |
---|---|---|
encoded_uri_component |
string | A URI component that has been encoded by encodeUriComponent() or by other means. |
Associated permissions
None.
encodeUri
Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI.
Example:
sendPixel('https://www.example.com/' + encodeUri(pathInput));
Syntax
encodeUri(uri)
Parameters
Parameter | Type | Description |
---|---|---|
uri |
string | A complete URI. |
Associated permissions
None.
encodeUriComponent
Returns an encoded Uniform Resource Identifier (URI) by escaping special characters. Returns a string that represents the provided string encoded as a URI.
Example:
sendPixel('https://www.example.com/?' + encodeUriComponent(queryInput));
Syntax
encodeUriComponent(str)
Parameters
Parameter | Type | Description |
---|---|---|
str |
string | A component of a URI. |
Associated permissions
None.
fromBase64
The fromBase64
API lets you to decode strings from their base64
representation. Returns undefined
when provided with invalid input.
Syntax
fromBase64(base64EncodedString)
Parameters
Parameter | Type | Description |
---|---|---|
base64EncodedString |
string | Base64 encoded string. |
Example
const fromBase64 = require('fromBase64');
const greeting = fromBase64('aGVsbG8=');
if (greeting === 'hello') {
// ...
}
Associated permissions
None
generateRandom
Returns a random number (integer) within the given range.
Syntax
generateRandom(min, max)
Parameters
Parameter | Type | Description |
---|---|---|
min |
number | Minimum potential value of the returned integer. |
max |
number | Maximum potential value of the returned integer. |
Associated permissions
None.
getContainerVersion
Returns an object containing data about the current container. The returned object will have the following fields:
{
containerId: string,
debugMode: boolean,
environmentName: string,
environmentMode: boolean,
previewMode: boolean,
version: string,
}
Example
const getContainerVersion = require('getContainerVersion');
const sendPixel = require('sendPixel');
if (query('read_container_data')) {
const cv = getContainerVersion();
const pixelUrl = 'https://pixel.com/' +
'?version=' + cv.version +
'&envName=' + cv.environmentName +
'&ctid=' + cv.containerId +
'&debugMode=' + cv.debugMode +
'&previewMode=' + cv.previewMode;
if (query('send_pixel', pixelUrl)) {
sendPixel(pixelUrl);
}
}
Syntax
getContainerVersion();
Associated permissions
getCookieValues
Returns the values of all cookies with the given name.
Syntax
getCookieValues(name[, decode])
Parameters
Parameter | Type | Description |
---|---|---|
name |
string | Name of the cookie. |
decode |
boolean | Controls whether the cookie values are to be decoded with JavaScript's decodeURIComponent() . Defaults to true . |
Associated permissions
getQueryParameters
Returns the first or all of the parameters for the current URL's queryKey
. Returns the first value from the queryKey
or an Array of values from the queryKey
.
Syntax
getQueryParameters(queryKey[, retrieveAll])
Parameters
Parameter | Type | Description |
---|---|---|
queryKey |
string | The key to read from the query parameters. |
retrieveAll |
boolean | Whether to retrieve all the values. |
For example, if the current URL is https://www.example.com/path?var=foo&var1=foo1&var=foo2&var=foo
, then:
getQueryParameters('var') == 'foo'
getQueryParameters('var', false) == 'foo'
getQueryParameters('var', null) == 'foo'
getQueryParameters('var', true) == ['foo', 'foo2', 'foo']
Associated permissions
get_url
must allow the query
component, and must specify the queryKey
in the allowed query keys (or allow any query key.)
getReferrerQueryParameters
The getReferrerQueryParameters
API acts the same way as getQueryParameters
, except it acts on the referrer instead of the current URL. Returns the first or all of the parameters for the given referrer's queryKey
. Returns the first value from the queryKey
or an Array of values from the queryKey
.
Syntax
getReferrerQueryParameters(queryKey[, retrieveAll])
Parameters
Parameter | Type | Description |
---|---|---|
queryKey |
string | The key to read from the query parameters. |
retrieveAll |
boolean | Whether to retrieve all the values. |
For example, if the referrer URL is https://www.example.com/path?var=foo&var1=foo1&var=foo2&var=foo
, then:
getReferrerQueryParameters('var') == 'foo'
getReferrerQueryParameters('var', false) == 'foo'
getReferrerQueryParameters('var', null) == 'foo'
getReferrerQueryParameters('var', true) == ['foo', 'foo2', 'foo']
Associated permissions
get_referrer
must allow the query
component, and must specify the queryKey
in the allowed query keys (or allow any query key.)
getReferrerUrl
Given a component type, the API reads the document object for the referrer and returns a string that represents a portion of the referrer. If no component is specified, full referrer URL is returned.
Syntax
getReferrerUrl([component])
Parameters
Parameter | Type | Description |
---|---|---|
component |
string | The component to return from the URL. Can be one of the following: protocol , host , port , path , query , extension . If component is undefined , null , or doesn't match one of these components, the entire URL will be returned. |
Associated permissions
get_referrer
must allow the query
component, and must specify the queryKey
in the allowed query keys (or allow any query key.)
getTimestamp
Deprecated. Prefer getTimestampMillis.
Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now()
.
Syntax
getTimestamp();
Associated permissions
None.
getTimestampMillis
Returns a number that represents the current time in milliseconds since Unix epoch, as returned by Date.now()
.
Syntax
getTimestampMillis();
Associated permissions
None.
getType
Returns a string describing the given value's type. Unlike typeof
, getType
differentiates between array
and object
.
Syntax
getType(data.someField)
Notes
The following table lists the strings returned for each input value.
Input Value | Result |
---|---|
undefined |
'undefined' |
null |
'null' |
true |
'boolean' |
12 |
'number' |
'string' |
'string' |
{ a: 3 } |
'object' |
[ 1, 3 ] |
'array' |
(x) => x + 1 |
'function' |
Associated permissions
None.
getUrl
Returns a string that represents all or a portion of the current URL, given a component type, and some configuration parameters.
Syntax
getUrl(component)
Parameters
Parameter | Type | Description |
---|---|---|
component |
string | The component to return from the URL. Must be one of: protocol , host , port , path , query , extension , fragment . If component is undefined , null , or doesn't match one of these components, the entire href value will be returned. |
Associated permissions
injectHiddenIframe
Adds an invisible iframe to the page.
Callbacks are given as function instances, and are wrapped in JavaScript functions that call through to them.
Syntax
injectHiddenIframe(url, onSuccess)
Parameters
Parameter | Type | Description |
---|---|---|
url |
string | The URL to be used as the value of the iframe's src attribute. |
onSuccess |
function | Called when the frame loads successfully. |
Associated permissions
injectScript
Adds a script tag to the page to load the given URL asynchronously. The callbacks are given as function instances, and are wrapped in JavaScript functions that call through to them.
Syntax
injectScript(url, onSuccess, onFailure[, cacheToken])
Parameters
Parameter | Type | Description |
---|---|---|
url |
string | The address of the script to be injected. |
onSuccess |
function | Called when the script loads successfully. |
onFailure |
function | Called when the script fails to load. |
cacheToken |
string | Optional string used to indicate the given URL should be cached. If this value is specified, only one script element will be created to request the JavaScript. Any additional attempts to load will result in the given onSuccess and onFailure methods being queued until the script loads. |
Associated permissions
JSON
Returns an object that provides JSON functions.
The parse()
function parses a JSON string to construct the value or object described by the string. If the value cannot be parsed (e.g. malformed JSON), the function will return undefined
. If the input value is not a string, the input will be coerced to a string.
The stringify()
function converts the input into a JSON string. If the value cannot be parsed (e.g. the object has a cycle), the method will return undefined
.
Syntax
JSON.parse(stringInput)
JSON.stringify(value);
Parameters
JSON.parse
Parameter | Type | Description |
---|---|---|
stringInput | any | The value to convert. If the value is not a string, the input will be coerced to a string. |
JSON.stringify
Parameter | Type | Description |
---|---|---|
value | any | The value to convert. |
Example
const JSON = require('JSON');
// The JSON input string is converted to an object.
const object = JSON.parse('{"foo":"bar"}');
// The input object is converted to a JSON string.
const str = JSON.stringify({foo: 'bar'});
localStorage
Returns an object with methods for accessing local storage.
Syntax
const localStorage = require('localStorage');
// Requires read access for the key. Returns null if the key does not exist.
localStorage.getItem(key);
// Requires write access for the key. Returns true if successful.
localStorage.setItem(key, value);
// Requires write access for the key.
localStorage.removeItem(key);
Associated permissions
Example
const localStorage = require('localStorage');
if (localStorage) {
const value = localStorage.getItem('my_key');
if (value) {
const success = localStorage.setItem('my_key', 'new_value');
if (success) {
localStorage.removeItem('my_key');
}
}
}
logToConsole
Logs arguments to the browser console.
Syntax
logToConsole(obj1 [, obj2,... objN])
Parameters
Parameter | Type | Description |
---|---|---|
obj1 [, obj2,... objN] |
any | Arguments |
Associated permissions
makeInteger
Converts the given value to a number (integer).
Syntax
makeInteger(value)
Parameters
Parameter | Type | Description |
---|---|---|
value |
any | The value to convert. |
Associated permissions
None.
makeNumber
Converts the given value to a number.
Syntax
makeNumber(value)
Parameters
Parameter | Type | Description |
---|---|---|
value |
any | The value to convert. |
Associated permissions
None.
makeString
Returns the given value as a string.
Syntax
makeString(value)
Parameters
Parameter | Type | Description |
---|---|---|
value |
any | The value to convert. |
Associated permissions
None.
makeTableMap
Converts a simple table object with two columns to a Map
. This is used to change a SIMPLE_TABLE
template field with two columns into a more manageable format.
For example, this function could convert a table object:
[
{'key': 'k1', 'value': 'v1'},
{'key': 'k2', 'value': 'v2'}
]
into a Map:
{
'k1': 'v1',
'k2': 'v2'
}
Returns an Object: The converted Map
if key-value pairs have been added to it, or null
otherwise.
Syntax
makeTableMap(tableObj, keyColumnName, valueColumnName)
Parameters
Parameter | Type | Description |
---|---|---|
tableObj |
List | The table object to convert. It's a list of maps where each Map represents a row in the table. Each property name in a row object is the column name, and the property value is the column value in the row. |
keyColumnName |
string | Name of the column whose values will become keys in the converted Map . |
valueColumnName |
string | Name of the column whose values will become values in the converted Map . |
Associated permissions
None.
Math
An object providing Math
functions.
Syntax
const Math = require('Math');
// Retrieve the absolute value.
const absolute = Math.abs(-3);
// Round the input down to the nearest integer.
const roundedDown = Math.floor(3.6);
// Round the input up to the nearest integer.
const roundedUp = Math.ceil(2.2);
// Round the input to the nearest integer.
const rounded = Math.round(3.1);
// Return the largest argument.
const biggest = Math.max(1, 3);
// Return the smallest argument.
const smallest = Math.min(3, 5);
// Return the first argument raised to the power of the second argument.
const powerful = Math.pow(3, 1);
// Return the square root of the argument.
const unsquared = Math.sqrt(9);
Parameters
Math functions parameters are converted to numbers.
Associated permissions
None.
queryPermission
Query the allowed and narrowed permissions. Returns a boolean: true
if a permission is granted, false
otherwise.
Syntax
queryPermission(permission, functionArgs*)
Parameters
Parameter | Type | Description |
---|---|---|
permission |
string | Name of the permission. |
functionArgs |
any | Function arguments vary based on the permission being queried. See Function Arguments below. |
Function Arguments
sendPixel
, injectScript
, injectHiddenIframe
: The second parameter should be a URL string.
writeGlobals
, readGlobals
: The second parameter should be the key being written or read.
readUrl
: No additional arguments are necessary to query whether the whole URL can be read. To query whether a given component can be read, pass the component name as the second argument:
if (queryPermission('readUrl','port')) {
// read the port
}
To check whether a specific query key is readable, pass the query key as the third parameter:
if (queryPermission('readUrl','query','key')) {
getUrlComponent(...);
}
Associated permissions
None.
readCharacterSet
Returns the value of document.characterSet
.
Syntax
readCharacterSet()
Parameters
None.
Associated permissions
readTitle
Returns the value of document.title
.
Syntax
readTitle()
Parameters
None.
Associated permissions
require
Imports a built-in function by name. Returns a function or an object that can be called from your program. Returns undefined when the browser does not support the built-in function.
Syntax
require(name)
Parameters
Parameter | Type | Description |
---|---|---|
name |
string | The name of the function to import. |
Example
const getUrl = require('getUrl');
const url = getUrl();
Associated permissions
None.
sendPixel
Makes a GET request to a specified URL endpoint.
Syntax
sendPixel(url, onSuccess, onFailure)
Parameters
Parameter | Type | Description |
---|---|---|
url |
string | Where to send the pixel. |
onSuccess |
function | Called when the pixel is sent successfully. |
onFailure |
function | Called when the pixel fails. |
Associated permissions
setCookie
Sets or deletes the cookie with the specified name, value, and options.
Syntax
setCookie(name, value[, options, encode])
Parameters
Parameter | Type | Description |
---|---|---|
name |
string | Name of the cookie. |
value |
string | Value of the cookie. |
options |
object | Specifies the Domain, Path, Expires, Max-Age, Secure, and SameSite attributes. (See Options, below.) |
encode |
boolean | Controls whether the cookie value is to be encoded with JavaScript's encodeURIComponent() . Defaults to true . |
- Domain: set by
options['domain']
property, if present. Set this value to'auto'
to try to write the cookie using the broadest possible domain, based on the document location. If that fails, it will try successively narrower subdomains. If all of those fail, it will try to write the cookie without a domain. If no value is set, this will try to write the cookie without a domain specified. Note: when a cookie without a domain specified is written todocument.cookie
, the user agent will default the cookie's domain to the host of the current document location. - Path: set by
options['path']
, if present. When a cookie without a path specified is written todocument.cookie
, the user agent will default the cookie's path to the path of the current document location. - Max-Age: set by
options['max-age']
, if present. - Expires: set by
options['expires']
, if present. If present, this must be a UTC-formatted date string.Date.toUTCString()
can be used to format aDate
for this parameter. - Secure: set by
options['secure']
, if present. - SameSite: set by
options['samesite']
, if present.
Associated permissions
setInWindow
Sets the given value in window
at the given key. By default this method won't set the value in the window
if there is already a value present. Set overrideExisting
to true
to set the value in the window
regardless of the presence of an existing value. Returns a boolean: true
if the value was set successfully, and false
otherwise.
Syntax
setInWindow(key, value, overrideExisting)
Parameters
Parameter | Type | Description |
---|---|---|
key |
string | The key in window to place the value at. |
value |
* | The value to set in window . |
overrideExisting |
boolean | The flag indicating that value should be set in window , regardless if there's a value there or not. |
Associated permissions
sha256
Calculates the SHA-256 digest of the input and invokes a callback with the digest encoded in base64.
Example:
sha256('inputString', (digest) => {
sendPixel('https://example.com/collect?id=' + digest);
data.gtmOnSuccess();
}, data.gtmOnFailure);
Syntax
sha256(input, onSuccess, onFailure = undefined)
Parameters
Parameter | Type | Description |
---|---|---|
input |
string | The string to calculate the hash for. |
onSuccess |
function | Called with the resulting digest, encoded in base64. |
onFailure |
function | Called if an error occurs while calculating the digest, or if the browser does not have native support for sha256. The callback is called with an object containing the name of the error, and the message. |
Associated permissions
None.
templateStorage
Returns an object with methods for accessing template storage. Template storage allows data to be shared across executions of a single template. Data stored in template storage persists for the lifetime of the page.
Syntax
const templateStorage = require('templateStorage');
templateStorage.getItem(key);
templateStorage.setItem(key, value);
templateStorage.removeItem(key);
// Deletes all stored values for the template.
templateStorage.clear();
Associated permissions
Example
const templateStorage = require('templateStorage');
const sendPixel = require('sendPixel');
// Ensure sendPixel is called only once per page.
if (templateStorage.getItem('alreadyRan')) {
data.gtmOnSuccess();
return;
}
templateStorage.setItem('alreadyRan', true);
sendPixel(
data.oncePerPagePixelUrl,
data.gtmOnSuccess,
() => {
templateStorage.setItem('alreadyRan', false);
data.gtmOnFailure();
});
toBase64
The toBase64
API lets you to encode a string into a base64 representation.
Syntax
toBase64(input)
Parameters
Parameter | Type | Description |
---|---|---|
input |
string | String to encode. |
Example
const toBase64 = require('toBase64');
const base64Hello = toBase64('hello');
Associated permissions
None
Test APIs
These APIs work with sandboxed JavaScript tests to build tests for custom templates in Google Tag Manager. These test APIs do not need a require()
statement. Learn more.
assertApi
Returns a matcher object that can be used to fluently make assertions about the given API.
Syntax
assertApi(apiName)
Parameters
Parameter | Type | Description |
---|---|---|
apiName
|
string | The name of the api to check; same string as passed
to require() . |
Matchers
Subject.wasCalled()
Subject.wasNotCalled()
Subject.wasCalledWith(...expected)
Subject.wasNotCalledWith(...expected)
Examples
assertApi('sendPixel').wasCalled();
assertApi('getUrl').wasNotCalled();
assertApi('makeNumber').wasCalledWith('8');
assertApi('setInWindow').wasNotCalledWith('myVar', 'theWrongValue');
assertThat
The assertThat
API is modeled after Google's Truth library. It returns an object that can be used to fluently make assertions about a subject's value. An assertion failure will immediately stop the test and mark it as failed. However, a failure in one test will not affect other test cases.
Syntax
assertThat(actual, opt_message)
Parameters
Parameter | Type | Description |
---|---|---|
actual |
any | The value to use in the fluent checks. |
opt_message |
string | Optional message to print if the assertion fails. |
Matchers
Matcher | Description |
---|---|
isUndefined() |
Asserts that the subject is undefined . |
isDefined() |
Asserts that the subject is not undefined . |
isNull() |
Asserts that the subject is null . |
isNotNull() |
Asserts that the subject is not null . |
isFalse() |
Asserts that the subject is false . |
isTrue() |
Asserts that the subject is true . |
isFalsy() |
Asserts that the subject is falsy. Falsy values are undefined , null , false , NaN , 0, and '' (empty string). |
isTruthy() |
Asserts that the subject is truthy. Falsy values are undefined , null , false , NaN , 0, and '' (empty string). |
isNaN() |
Asserts that the subject is the value NaN. |
isNotNaN() |
Asserts that the subject is any value besides NaN. |
isInfinity() |
Asserts that the subject is positive or negative Infinity. |
isNotInfinity() |
Asserts that the subject is any value besides positive or negative Infinity. |
isEqualTo(expected) |
Asserts that the subject is equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
isNotEqualTo(expected) |
Asserts that the subject is not equal to the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
isAnyOf(...expected) |
Asserts that the subject is equal to one of the given value. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
isNoneOf(...expected) |
Asserts that the subject is not equal to any of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
isStrictlyEqualTo(expected) |
Asserts that the subject is strictly equal (=== ) to the given value. |
isNotStrictlyEqualTo(expected) |
Asserts that the subject is not strictly equal (!== ) to the given value. |
isGreaterThan(expected) |
Asserts that the subject is greater than (> ) the given value in an ordered comparison. |
isGreaterThanOrEqualTo(expected) |
Asserts that the subject is greater than or equal to (>= ) the given value in an ordered comparison. |
isLessThan(expected) |
Asserts that the subject is less than (< ) the given value in an ordered comparison. |
isLessThanOrEqualTo(expected) |
Asserts that the subject is less than or equal to (<= ) the given value in an ordered comparison. |
contains(...expected) |
Asserts that the subject is an array or string that contains all of the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
doesNotContain(...expected) |
Asserts that the subject is an array or string that contains none of the given values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
containsExactly(...expected) |
Asserts that the subject is an array that contains all of the given values in any order and no other values. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
doesNotContainExactly(...expected) |
Asserts that the subject is an array that has contains a different set of values from the given values in any order. This is a value comparison, not a reference comparison. The contents of objects and arrays are compared recursively. |
hasLength(expected) |
Asserts that the subject is an array or string with the given length. The assertion always fails if the value is not an array or string. |
isEmpty() |
Asserts that the subject is an array or string that is empty (length = 0). The assertion always fails if the value is not an array or string. |
isNotEmpty() |
Asserts that the subject is an array or string that is not empty (length > 0). The assertion always fails if the value is not an array or string. |
isArray() |
Asserts that the type of the subject is an array. |
isBoolean() |
Asserts that the type of the subject is a boolean. |
isFunction() |
Asserts that the type of the subject is a function. |
isNumber() |
Asserts that the type of the subject is a number. |
isObject() |
Asserts that the type of the subject is an object. |
isString() |
Asserts that the type of the subject is a string. |
Examples
assertThat(undefined).isUndefined();
assertThat(id, 'ID must be defined').isDefined();
assertThat(null).isNull();
assertThat(undefined).isNotNull();
assertThat(true).isTrue();
assertThat(false).isFalse();
assertThat(1).isTruthy();
assertThat('').isFalsy();
assertThat(1/0).isInfinity();
assertThat(0).isNotInfinity();
assertThat(-'foo').isNaN();
assertThat(100).isNotNaN();
assertThat(sentUrl).isEqualTo('https://endpoint.example.com/?account=12345');
assertThat(category).isNotEqualTo('premium');
assertThat(5).isAnyOf(1, 2, 3, 4, 5);
assertThat(42).isNoneOf('the question', undefined, 41.9);
assertThat('value').isStrictlyEqualTo('value');
assertThat('4').isNotStrictlyEqualTo(4);
assertThat(['a', 'b', 'c']).contains('a', 'c');
assertThat(['x', 'y', 'z']).doesNotContain('f');
assertThat(['1', '2', '3']).containsExactly('3', '2', '1');
assertThat(['4', '5']).doesNotContainExactly('4');
assertThat('a string').hasLength(8);
assertThat([]).isEmpty();
assertThat('another string').isNotEmpty();
fail
Immediately fails the current test and prints the given message, if supplied.
Syntax
fail(opt_message);
Parameters
Parameter | Type | Description |
---|---|---|
opt_message |
string | Optional error message text. |
Example
fail('This test has failed.');
mock
The mock
API allows you to override the behavior of Sandboxed APIs. The mock API is safe to use in template code, but it is non-operational when not in test mode. Mocks are reset before each test is run.
Syntax
mock(apiName, returnValue);
Parameters
Parameter | Type | Description |
---|---|---|
apiName
|
string | The name of the API to mock; same string as
passed to require() |
returnValue
|
any | The value to return for the API or a function
called in place of the API. If returnValue
is a function, that function is called in
place of the Sandboxed API; if returnValue
is anything other than a function, that value
is returned in place of the Sandboxed API. |
Examples
mock('encodeUri', "https://endpoint.example.com/?account=12345");
mock('sendPixel', function(url, onSuccess, onFailure) {
onSuccess();
});
runCode
Runs the code for the template, i.e. the content of the Code tab, in the current test environment with a given input data object.
Syntax
runCode(data)
Parameters
Parameter | Type | Description |
---|---|---|
data |
object | Data object to be used in the test. |
Return Value
Returns the value of a variable for variable templates; returns undefined
for all other template types.
Example
runCode({field1: 123, field2: 'value'});