Google Tag Manager (GTM) has updated its custom template APIs with a new mockObject feature. This addition allows developers to write unit tests for complex APIs that return objects, such as Firestore and LocalStorage.
Key Features of the mockObject API
- Object Mocking: Overrides the behavior of Sandboxed APIs that return objects.
- Test Mode Exclusive: The API only operates in test mode.
- Automatic Reset: Mocks reset before each test run.
How It Works
The mockObject API uses this syntax:
mockObject(apiName, objectMock);
- apiName (string): The API name to mock, matching the string passed to require()
- objectMock (object): The value or function to return for the API
Benefits for Developers
- Testing Accuracy: Tests can use actual template code instead of dummy values.
- Debugging: Precise mocking helps identify issues in complex templates.
- Reliability: Comprehensive testing leads to more dependable custom templates.
Example Use Case
Here's an example demonstrating how to simulate write and read operations for Firestore in tests:
const storage = {};
let firestoreId = 1;
function asTestPromise(result) {
return {
then: (callback) => callback(result)
};
}
mockObject('Firestore', {
write: (collection, input) => {
storage[collection + '/' + (++firestoreId)] = input;
return asTestPromise(firestoreId);
},
read: (document) => asTestPromise({data: storage[document]})
});
This addition to Google Tag Manager's testing capabilities allows for more thorough testing of custom templates, particularly those using complex APIs that return objects. An example of mocking the Firestore API: