2 min read

Test Mode Google Apps Script

Test Mode Google Apps Script

Google Apps Script does not have a well established testing story. It is crucial to test Apps Script code without actually changing production data or triggering emails to customers. This is where the isTestMode function becomes useful.

/**
 * Checks if the test mode is enabled. Manually enable / disable test mode in Project Settings -> Script Properties
 * 
 * Copy this function into a .gs file in your Google Apps Script project.
 *
 * @returns {boolean} - True if the test mode is enabled, false otherwise.
 */
function isTestMode() {
  return PropertiesService.getScriptProperties().getProperty('testMode') === 'true';
}

The isTestMode function serves as a switch between testing and production modes for your Google Apps Script. When your script is in test mode, it executes code in a safe, controlled environment. This means the script can work with dummy data or perform actions that do not impact users or customers. For example, if your script sends emails, in test mode, it won't actually send those emails out. Or if your script modifies data in a Google sheet, in testing mode, it either avoids making changes or manipulates a separate test sheet to preserve your actual data.

When not in test mode, your script can perform its intended tasks. Emails are sent, data is modified.

You can manually enable or disable test mode using the Script Properties within the Project Settings. When you set the testMode property to true, you activate test mode, and the isTestMode function will return true. If you set testMode to any other value, isTestMode will return false, implying that the script is not in test mode.

When you call isTestMode(), it queries the Project's Script Properties for the testMode key and checks if the associated value equals 'true'. If it does, the function returns true, indicating the script is in test mode. If not, it returns false, implying the script is not in test mode.

Using isTestMode

In your Google Apps Script, you can use isTestMode() to check if you are in test mode and conditionally execute actions accordingly. Here is an example:

if (isTestMode()) {
  // We're in testing mode! We should avoid actions that have real-world impact.
  Logger.log('Test Mode: The email would be sent to: john.doe@example.com');
} else {
  // We're in production mode! It's okay to perform our real-world actions so we are sending an email to john.doe@example.com.
  MailApp.sendEmail('john.doe@example.com', 'Hello!', 'This is a production email.');
}

If you are looking for help using Google App Script to automate a workflow, feel free to reach out.