The GAS開発 in 2016 その4
前回実際にコードを書いて、GAS向けにビルド、アップロードする
今回はGASの独自機能をシミュレートするモックを作成して、ローカルでのテストを可能にします。
前回の doGet 関数を正規の出力を出すように作成
dev/index.js
@@ -xx,yyy +xx,zzz @@ if (query.parameter.token !== global.token) { log.e('Bad token access'); - return false; + return ContentService + .createTextOutput(JSON.stringify({content: 'Bad access'})) + .setMimeType(ContentService.MimeType.JSON); } - return true; + return ContentService + .createTextOutput(JSON.stringify({content: 'Process OK'})) + .setMimeType(ContentService.MimeType.JSON);
この ContentService はGAS上だけで動くAPIのためモックの作成が必要です。 また、前回の Log.js で用いた DocumentApp も同様。
作業ディレクトリのトップに GlibMock.js を作成
const gas = require('gas-local'); const fs = require('fs'); gas.globalMockDefault.Logger.enabled = false; const defMock = gas.globalMockDefault; const customMock = { ContentService: { createTextOutput: function (text) { return { setMimeType: function (mimeType) { return { content: text, mime: mimeType, }; }, }; }, MimeType: { JSON: 'application/javascript' }, }, DocumentApp: { openById: function (fileId) { return { getBody: function () { return { appendParagraph: function (text) { console.log(text); }, }; }, }; }, }, __proto__: defMock, }; module.exports = gas.require('./src', customMock);
このモックを使って、GAS向けにビルドされたスクリプト (src/main.js) をテストするスクリプトを test/test-main.js として作成します。
const assert = require('power-assert'); const glib = require('../GLibMock.js'); describe('doGet', function () { it('should return to BAD ACCESS', function () { const query = { parameter: {}, contextPath: '', contentLength: -1, queryString: '', parameters: {}, }; assert.equal(glib.doGet(query).content, JSON.stringify({ content: 'Bad access' })); }); it('should return to PROCESS OK', function () { const query = { parameter: { token: 'TEST_TOKEN' }, contextPath: '', contentLength: -1, queryString: 'token=TEST_TOKEN', parameters: { token: ['TEST_TOKEN'] }, }; assert.equal(glib.doGet(query).content, JSON.stringify({ content: 'Process OK' })); }); });
テストを実行するために、 package.json を書き換えます。
package.json
@@ -xx,yyy +xx,zzz @@ "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "test": "npm run build && mocha --require intelli-espower-loader", "build": "browserify dev/index.js -t babelify -p gasify -o src/main.js", "upload": "gapps upload", "watch": "watchify dev/index.js -t babelify -p gasify -p src/main.js" },
ここまで出来たらタスクの実行から npm test を選択
テスト結果が 2passing と出ればテストが通ったことになります。 また、Google ドキュメントに出力していたログがテスト中はターミナルに表示されていることも確認できます。
前回と同様に npm upload を実行すればGoogleのサーバーにアップロードされますので一緒に動作確認しましょう
最後にGithubにcommit, push して終わり
※最初にpush したときは必ずGithubのWebからAPIキーなどが公開されていないか確認しましょう
今回つかったリポジトリはこちら