After using AI extensively to generate and refactor Google Apps Script code, I noticed a recurring problem: the code often works, but it is not always written with Apps Script performance in mind.
Although Google provides official Apps Script documentation, the ecosystem has fewer practical resources and examples than many mainstream JavaScript platforms. AI-generated scripts can therefore contain unnecessary service calls, inefficient spreadsheet operations or code that becomes difficult to maintain as the project grows.
Rather than repeating the same instructions in every prompt, I created google-apps-script-standards, an open-source Agent Skill that helps AI coding agents write clean, optimized and maintainable Google Apps Script code. It brings together the development practices I use in my own projects.
What is an Agent Skill?
An Agent Skill is a reusable set of instructions, typically organized around a SKILL.md file. It gives a coding agent specific development guidelines without requiring you to repeat them in every prompt. It is not an Apps Script library and does not run inside your script.
Google Apps Script performance and coding best practices
Code structure: centralized configuration, consistent entry-point naming and typed JSDoc for editor autocomplete.
Google Sheets performance: batch operations, column lookup by header and targeted writes that avoid overwriting unrelated cells.
Long-running scripts: checkpoints, retries that account for quotas and structured Cloud Logging summaries.
Web app performance: lightweight initial payloads and fewer client-to-server calls through grouped google.script.run requests.
The objective is to make generated code more efficient, maintainable and suitable for the Apps Script execution environment.
Select your coding agent when prompted. Alternatively, download the repository and copy the entire skills/google-apps-script-standards directory into your agent’s skills directory. The location depends on the agent you use.
How to optimize Google Apps Script code with AI
Once installed, ask your coding agent to apply the skill to an existing project or a new implementation. For example:
Use google-apps-script-standards to optimize my Apps Script code. Batch spreadsheet operations, identify columns by header and preserve existing formulas outside the target columns.
A common example is slow Google Sheets automation. Calling getValue() or setValue() repeatedly inside a loop creates unnecessary calls to the spreadsheet service. Where appropriate, the agent should read the data with getValues(), process it in JavaScript arrays or maps, and write the results with setValues(). This reduces service calls without changing the intended result. For targeted updates, it should also avoid overwriting unrelated cells or formulas.
Review the proposed changes and test them before deploying. The skill provides development guidance; it does not guarantee performance improvements or correctness.
Use the skill with VS Code and clasp
If you are still developing directly in the Apps Script editor, follow my guide to Google Apps Script in VS Code with clasp to set up a local development environment where you can work with coding agents and reusable skills.
When your Apps Script project is just one tiny function attached to a Sheet, you can get away with “click Run and hope for the best”.
But as soon as your codebase grows, multiple files, complex business rules, integrations with Sheets, Docs, external APIs, that approach stops scaling. A small change in one function can silently break something completely different.
That’s where unit testing in Google Apps Script comes in.
In this article, we’ll cover:
What unit testing is and why it matters for Apps Script
The current landscape of unit testing solutions for GAS (QUnitGS2, GasT, Utgs, Jest + clasp, etc.)
Classic unit testing principles adapted to Apps Script (AAA, dependency injection)
How to use QUnitGS2 / QUnit2GS to build a proper test suite in Apps Script
A lightweight console-based test runner that runs all test_ functions and logs PASS/FAIL in the execution log
By the end, you’ll have both a full-featured QUnit setup and a “zero-UI” runner you can use as a quick safety net in any project.
What is unit testing and why is it important?
Unit testing is the practice of testing small, isolated pieces of code (units), usually at the function level.
A typical unit test:
Calls a function with some inputs
Compares the result to an expected value
Fails loudly if they don’t match
In JavaScript (and therefore Apps Script), a unit test with QUnit looks like this:
QUnit.test('add() adds two numbers', (assert) => {
const result = add(1, 2);
assert.equal(result, 3, '1 + 2 should equal 3');
});
Why unit testing is especially useful in Google Apps Script projects:
Catch regressions early. When you refactor a Sheets automation or a Docs generator, tests tell you if something broke immediately instead of your users or clients discovering it later.
Refactor with confidence. You can rename functions, split files, change logic – and rely on tests as a safety net.
Executable documentation. A test like test_shouldApplyDiscountForTotalsOver1000 is more explicit than a vague comment buried in the code.
Faster debugging loops. Instead of manually re-running forms or simulating UI flows, you run the test suite and see exactly which scenario fails.
In “normal” JavaScript environments (Node/React), developers use tools like Jest, Mocha, QUnit, Ava… but Apps Script runs in a special environment that introduces a few constraints.
Limitations of Apps Script and existing unit testing solutions
Building a reliable unit testing structure in Google Apps Script (GAS) is essential for maintaining complex projects. But Apps Script is not a standard Node.js runtime:
No native local file system
No npm test directly inside the IDE
Limited setTimeout / async patterns
Heavy reliance on global services like SpreadsheetApp, DriveApp, MailApp, etc.
Because of that, unit testing solutions tend to fall into two big families:
In-GAS frameworks – tests run on Google’s servers inside the Apps Script runtime
Local testing – you pull code down with clasp and test it with Node tools, mocking Google services
Lightweight libs focused on simple assertions and PASS/FAIL logs in Logger.log.
Very easy to drop into any script, no web deployment required.
No GUI, you manage structure and conventions yourself.
Local testing with clasp + Jest/Ava
With the clasp CLI you can clone your Apps Script project locally, and then use any Node test framework you like (Jest, Ava, etc.) with mocks for Google services.
How it works
Use clasp to pull your code locally.
Write Jest/Ava tests.
Mock things like SpreadsheetApp and UrlFetchApp.
Run npm test locally.
Pros
Full Node ecosystem (TypeScript, Jest watch mode, coverage reports, CI/CD, VS Code integration).
Cons
Higher setup cost, especially for mocking Google services accurately.
Best suited to modular projects where business logic is already decoupled from Apps Script services.
Quick conclusion
If you want:
A visual, browser-based test runner → QUnitGS2 / QUnit2GS is an excellent choice
A blazing-fast, Node-like experience for pure logic → clasp + Jest is great.
A quick in-editor check that runs functions and logs results → a small custom console runner (or Utgs/bmUnitTest) is the most direct option.
In the rest of this article, we’ll combine both worlds:
QUnitGS2 for a “real” test suite with a UI
A tiny log-based test runner you can drop into any project
Classic unit testing principles in the Apps Script world
Before we jump into QUnit and custom runners, it’s worth aligning on some basic testing principles and how they apply to Apps Script.
AAA: Arrange, Act, Assert
A readable test follows the AAA pattern:
Arrange – set up inputs, initial state, mocks
Act – call the function under test
Assert – verify the result (return value or side effect)
Example (pseudo-code):
function test_addTwoNumbers() {
// Arrange
const a = 2;
const b = 3;
const expected = 5;
// Act
const actual = add(a, b);
// Assert
assert(actual, expected, 'add() should return 5 for (2, 3)');
}
Labeling those three steps makes your Apps Script tests much easier to read and maintain.
Isolation and dependency injection in Apps Script
True unit tests should focus on one unit of logic at a time. That’s tricky in Apps Script because your code often calls global services directly:
We’ll define a simple pure function to keep the focus on testing:
/**
* Calculates the total amount after applying a percentage discount.
*
* @param {number} amount - Base amount before discount.
* @param {number} discountPercent - Discount percentage between 0 and 100.
* @return {number} The discounted amount, rounded to 2 decimals.
* @throws {Error} If amount or discountPercent are invalid.
*/
function calculateDiscountedTotal(amount, discountPercent) {
if (typeof amount !== 'number' || Number.isNaN(amount) || amount < 0) {
throw new Error('amount must be a non-negative number');
}
if (
typeof discountPercent !== 'number' ||
Number.isNaN(discountPercent) ||
discountPercent < 0 ||
discountPercent > 100
) {
throw new Error('discountPercent must be between 0 and 100');
}
const discount = (amount * discountPercent) / 100;
const total = amount - discount;
return Number(total.toFixed(2));
}
Wire up the QUnit web app
Add this in (for example) QUnitRunner.gs:
/* global QUnitGS2 */
/**
* QUnit instance provided by QUnitGS2.
* @type {QUnit}
*/
const QUnit = QUnitGS2.QUnit;
/**
* Web app entry point that runs the QUnit test suite and returns HTML results.
*
* @param {Object} e - Web app request event.
* @return {Object} HTML output with QUnit UI.
*/
function doGet(e) {
QUnitGS2.init();
registerTests();
QUnit.start();
return QUnitGS2.getHtml();
}
/**
* Called from the client-side HTML to retrieve QUnit results
* after the server-side test run completes.
*
* @return {Object} JSON results from the QUnitGS2 server.
*/
function getResultsFromServer() {
return QUnitGS2.getResultsFromServer();
}
Define QUnit tests
Now create registerTests() and write your tests:
/**
* Registers all QUnit test modules.
*/
function registerTests() {
QUnit.module('calculateDiscountedTotal', () => {
QUnit.test('returns original amount when discount is 0%', (assert) => {
const result = calculateDiscountedTotal(100, 0);
assert.equal(result, 100, '100 with 0% discount should stay 100');
});
QUnit.test('applies percentage discount correctly', (assert) => {
const result = calculateDiscountedTotal(200, 10);
assert.equal(result, 180, '10% discount on 200 should be 180');
});
QUnit.test('rounds to 2 decimals', (assert) => {
const result = calculateDiscountedTotal(99.99, 5);
assert.equal(result, 94.99, 'Should round result to 2 decimals');
});
QUnit.test('throws on negative amount', (assert) => {
assert.throws(
() => calculateDiscountedTotal(-10, 10),
/amount must be a non-negative number/,
'Negative amounts should throw'
);
});
QUnit.test('throws when discount > 100%', (assert) => {
assert.throws(
() => calculateDiscountedTotal(100, 150),
/discountPercent must be between 0 and 100/,
'Discount > 100% should throw'
);
});
});
}
Deploy as a web app and run tests
Deploy → New deployment → Web app
Execute as: your account
Who has access: as you prefer (e.g. “Only me”)
Copy the web app URL and open it in your browser
QUnitGS2 will:
Initialize QUnit
Run your registerTests()
Show a full QUnit HTML report with passing/failing tests
A simple console-based unit test runner (no web app required)
Sometimes you just want a quick pass/fail check in the Execution log without deploying a web app or integrating a full framework.
The script below implements a self-contained test runner that:
Looks for all global functions whose names start with test_
Runs them one by one
Logs PASS / FAIL and a short summary in the Apps Script execution log
// --- TEST UTILITIES: Place this in a file named 'TestRunner.gs' ---
/** @type {string} */
const TEST_PREFIX = 'test_';
/**
* Checks if two values are strictly equal and logs a PASS/FAIL message.
*
* @param {unknown} actual - The value returned by the function under test (Act).
* @param {unknown} expected - The predetermined correct value (Arrange).
* @param {string} message - Description of the assertion.
* @return {boolean} True if the assertion passes, false otherwise.
*/
function assert(actual, expected, message) {
if (actual === expected) {
Logger.log(`✅ PASS: ${message}`);
return true;
}
Logger.log(`❌ FAIL: ${message} - Expected: ${expected}, Actual: ${actual}`);
return false;
}
/**
* Iterates through all global functions and runs those prefixed with 'test_'.
* This acts as the central test runner.
*
* Run this manually from the Apps Script editor to execute the whole suite.
*/
function runAllTests() {
Logger.log('====================================');
Logger.log('🚀 STARTING UNIT TEST SUITE');
Logger.log('====================================');
let totalTests = 0;
let passedTests = 0;
let failedTests = 0;
const globalScope = typeof globalThis !== 'undefined' ? globalThis : this;
// Scan global functions and execute those starting with TEST_PREFIX.
for (const key in globalScope) {
if (Object.prototype.hasOwnProperty.call(globalScope, key)) {
const candidate = globalScope[key];
if (typeof candidate === 'function' && key.startsWith(TEST_PREFIX)) {
const testName = key;
Logger.log(`\n--- Running: ${testName} ---`);
try {
candidate();
passedTests++;
} catch (e) {
failedTests++;
const message = e instanceof Error ? e.message : String(e);
Logger.log(`💥 ERROR in ${testName}: ${message}`);
}
totalTests++;
}
}
}
Logger.log('\n====================================');
Logger.log(`RESULTS: ${totalTests} tests run`);
Logger.log(`PASSED: ${passedTests}`);
Logger.log(`FAILED: ${failedTests}`);
Logger.log('====================================');
}
Paste TestRunner.gs into your Apps Script project.
Add tests by creating functions whose names start with test_ (in the same project).
In the editor, select runAllTests and click Run ▶️.
Open View → Logs to see a step-by-step PASS/FAIL log and the final summary.
This gives you:
A very fast feedback loop while coding
No web app deployment required
A simple way to run a quick suite every time you touch the script
If you like this pattern, you can evolve it:
Add more assertion helpers (assertNotEquals, assertTrue, assertDeepEqual, …)
Add timing information per test
Exit early if a critical test fails (for long suites)
Putting it together
There’s no single “right” way to do unit testing in Google Apps Script, but a good strategy looks like this:
Use pure functions + dependency injection for your core business logic
Cover that logic with tests – either with QUnitGS2 (web UI) or your own console runner
Keep Apps Script service calls (SpreadsheetApp, DriveApp, etc.) thin and easy to mock
For bigger projects or front-end code, consider clasp + Jest and a local toolchain
Start small: pick one critical module (invoice calculation, validation rules, date logic…), write a handful of tests, and get used to running them every time you make a change.
Once you’ve seen a refactor go through while your QUnitGS2 panel and/or console runner stays fully green, you’ll never want to go back to “click Run and cross your fingers” again.
If you work on Google Workspace automation, sooner or later the online editor slows you down.
clasp (Command Line Apps Script Projects) lets you develop Apps Script locally, use VS Code, commit to Git, automate deployments, and generally work like a modern JS team. This guide covers installation, daily commands, project structure, TypeScript, logs, deploys, and real-world troubleshooting (including Windows/PowerShell quirks) so you can ship faster and safer.
What is clasp (and why use it)?
clasp is Google’s official CLI for Apps Script. It syncs code between your local folder and your Script project, manages versions/deployments, and unlocks editor-quality DX in VS Code (intellisense, linting, formatting, test runners, etc.). Core benefits:
Local dev + Git: edit with your toolchain, review PRs, branch safely.
Faster iteration: push/pull instead of copy/paste.
Typed workflows: use TypeScript + @types/google-apps-script.
Automations: wire into CI to version & deploy.
Prerequisites
Node.js (current LTS recommended) and npm.
Enable “Apps Script API” for your account at Apps Script > Settings > Enable Apps Script API (one-time).
Install & authenticate
npm install -g @google/clasp
clasp -v
clasp login
clasp login opens a browser to authorize your Google account and stores a credential file named .clasprc.json (password-like; don’t commit it). On some commands you may also see a project-local.clasprc.json—more on this in Troubleshooting.
Create or clone a project
Create a brand new script in the current folder:
mkdir my-script && cd my-script
clasp create --type standalone --title "My Script"
appsscript.json – the Apps Script manifest (scopes, time zone, etc.) You can also clone an existing project if you have the scriptId:
clasp clone <SCRIPT_ID>
Daily workflow (push/pull/run/logs/open)
# Pull remote changes (online editor → local)
clasp pull
# Push local changes (local → Apps Script)
clasp push
# Run a server-side function
clasp run myFunction
# Tail logs (Cloud Logging)
clasp logs --watch
# Open the project in the web editor
clasp open
Tips:
Use clasp push --watch during rapid editing.
If clasp run complains about auth, see the Local vs Global .clasprc note below.
Smart project structure with rootDir
Want clean source in src/ and compiled output in build/? Configure rootDir in .clasp.json:
clasp will sync the rootDir to Apps Script, your source can live elsewhere and be built into build/. There’s also filePushOrder when you must guarantee upload order (rare, but handy).
Ignore junk with .claspignore (similar to .gitignore):
Set outDir to build and target ES2019+ in tsconfig.json.
2. Point .clasp.json → "rootDir": "build", "fileExtension": "ts" (above). 3. Now write .ts in src/, compile to build/, then clasp push. The @types/google-apps-script package gives VS Code autocompletion for Services like SpreadsheetApp, DriveApp, etc
clasp deploy creates a version and a deployment in one step—ideal for Web Apps where you need a stable URL tied to a version. You can manage multiple deployments (e.g., dev vs prod).
Note: Web Apps also require you to set Execute as / Who has access in the online editor’s Deploy → Manage deployments once. After that you can update via CLI.
Working in VS Code (snappy checklist)
Install ESLint + Prettier to keep Apps Script code consistent.
Use “JavaScript and TypeScript Nightly” for latest TS features.
Add @types/google-apps-script for smart autocompletion.
Optional: a minimal GAS snippets extension can speed boilerplate.
Useful commands you’ll actually use
clasp list # list your scripts clasp status # see local vs remote diffs clasp apis enable sheets # enable Advanced Service / API in the project clasp open --webapp # jump straight to Web App deploy screen clasp help # docs for any command
(Availability of some subcommands can change; always check clasp help and the README.)
CI/CD with GitHub Actions (or Jenkins)
You can deploy from CI by injecting CLASPRC_JSON (the contents of your .clasprc.json after clasp login) as a secret:
This pattern mirrors community guidance for headless deploys. It relies on user OAuth tokens (service-account login isn’t officially supported by clasp today). Rotate tokens/secrets carefully.
Subtle but important things most guides miss
1) Local vs Global .clasprc.json Some commands (notably clasp run) historically looked for a project-local.clasprc.json. If you see “Could not read API credentials” even though you ran clasp login, try placing the same file both in ~/.clasprc.jsonand your project folder. This quirk appears mostly on Windows.
2) .clasp.json + rootDir behaviors The rootDir controls which local directory is synced. If your files don’t upload, double-check the path and where .clasp.json lives—there have been behavior changes across versions; keep it simple: put .clasp.json in your project root and use a plain relative rootDir.
3) Don’t commit secrets Never commit .clasprc.json. Treat it like a password. In CI, store its contents as a secret (base64 if you prefer), then reconstruct it in the build step.
4) Logs aren’t Stackdriver anymore clasp logs streams Cloud Logging for the project; it’s the fastest way to see console.log output from deployed code. Use --watch during debugging.
5) Advanced Services vs. Google APIs Enabling an “Advanced Service” (e.g., Drive) within appsscript.json is distinct from enabling the underlying Google API. You can use clasp apis enable <name> to help, but you may still need to confirm in the console the first time.
Troubleshooting (copy/paste savers)
“Unexpected token … is not valid JSON” on login Your .clasprc.json is corrupt (often due to accidental binary/encoding writes or half-written file). Fix: delete both local and home copies, then clasp login again. Ensure your shell didn’t write non-text bytes into the file (common when redirecting Windows commands). (General JSON error context; root cause is a malformed cred file.)
“Could not read API credentials / are you logged in globally?” Create both: ~/.clasprc.json and ./.clasprc.json (project root) by copying the home one locally. Then retry clasp run / clasp versions.
Clone says .clasp.json already exists clasp clone wants a clean directory. Create a new empty folder, cd into it, then run clasp clone <SCRIPT_ID>.
Push/pull not picking your compiled files Confirm rootDir in .clasp.json points to your build output (not src/). Re-build, then clasp push.
This gives you a single npm run push that compiles and syncs in one go. (Versions differ—adjust semvers.)
VS Code productivity add-ons (optional but nice)
ESLint with eslint-config-google for consistent style.
Jest for pure functions (keep Apps Script globals mocked).
EditorConfig for team consistency. (Use sparingly to keep your repo lean—your readers love vanilla setups.) (General ecosystem advice; no citation required.)
If the Apps Script online editor is your bike, clasp + VS Code is your electric bike: same destination, much faster and safer.
With a local workflow, Git history, TypeScript typings, and one-command deploys, you’ll spend less time copy-pasting and more time shipping reliable Google Workspace automations. The subtle bits, rootDir, .clasprc.json placement, and deployment versions, are where most teams stumble; now you’ve got them covered.
If you found this guide useful, bookmark it, then try converting one existing script to the clasp workflow. You’ll feel the speedup on day one.