I realy like Google Apps Script. I think it’s a powerfull tool for entreprises needs. But there is a major risk on build a complex application on Google Apps Script : Maintenability.
Indeed, Google Apps Script is basicly javascript and it is very easy to build ugly and bad test code with Javascript.
Refactoring is a good way to keep code clean. If you want to refactor with zen spirit, it is good thing to have unit tests on your code.
There is unit test library for Javascript like google-js-test, developped by Google, but I would like something more integrated.
That’s why I start to developpe my own library : GASUnit.
Files organisation
I separate code in 3 files :
- a file for the code to test
- a file for the test code
- a file for the library
Another advantage of this option, I didn’t need to copy/paste the library content in all project when I make a change.
Structure of a test file
- The library import
- The tests method
- The assertions
- The run method
var gasunit = UrlFetchApp.fetch("http://gasunit.googlecode.com/svn/trunk/gasunit.js").getContentText(); eval(gasunit);
var gasunit = UrlFetchApp.fetch("http://gasunit.googlecode.com/svn/trunk/gasunit.js").getContentText(); eval(gasunit); var userTest = { testIsAdult : function(){ var user = new User("Doe","John","19"); assertTrue(user.isAdult()); }, testIsNotAdult : function(){ var user = new User("Doe","John","17"); assertFalse(user.isAdult()); }, testRecordUser : function(){ var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); sheet.clear(); var user = new User("Doe","John","17"); user.record(sheet); assertCellContentEqual(sheet, "A1","Doe"); }, testRecordUserColorLine : function(){ var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); sheet.clear(); var user = new User("Doe","John","17"); user.record(sheet); assertCellColorEqual(sheet, "A1","#cccccc"); } }; function main(){ GASUnit.runTest(userTest); }
I add at the end of the script a main function to declare tests to execute.
Test results
When you run the test, the library create a new sheet for output.
You can see the results on this capture :
Fantastic submit, very informative. I wonder why the other experts of this sector don’t realize this. You must continue your writing. I’m sure, you’ve a huge readers’ base already!|What’s Going down i’m new to this, I stumbled upon this I have found It absolutely useful and it has aided me out loads. I’m hoping to give a contribution & help other customers like its aided me. Great job.
Hi,
Why you use fetch and eval instead of using the standard versioning and library mechanism provided by Apps Script platform (http://googleappsdeveloper.blogspot.com.br/2012/05/introducing-versions-and-libraries-in.html)?
Thanks,
Mael
Hi,
The reason is that this mecanism doesn’t exist when I first developpe this code.
Benjamin