Jest + TypeScript でテストできるようにする

 

 

TypeScriptのテストといえばJestなのかな?と思って導入してみました!
JavaScriptのみの場合は簡単だったんですが、TypeScriptの時はちょっと手こずったので残します😇

Jestとは❓

https://jestjs.io/docs/getting-started

導入手順📲

1️⃣ Jestをinstallする(JavaScriptテスト実行はここまででok👌)

$ npm install --save-dev jest
$ vi package.json //npm testでテスト実行できるようにする
{
  "devDependencies": {
    "jest": "^27.5.1"
- }
+ },
+ "scripts": {
+   "test": "jest"
+ }
}

$ npm test //JSのテスト実行できた〜🙌🙌🙌

> test
> jest

 PASS  ./sum.test.js
  ✓ adds 1 + 2 to equal 3 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.48 s
Ran all test suites.

2️⃣ TypeSciptでもJestでテスト実行できるようにする

TypeScriptだと以下のエラーが出たので調整する

$ npm test

> test
> jest

 FAIL  ./ts-sum.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/kin29/jest-test/ts-sum.test.ts:1
    ({"Object.":function(module,exports,require,__dirname,__filename,jest){import { TsSum } from "./ts-sum";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)

 PASS  ./sum.test.js

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.04 s
Ran all test suites.

tscコマンドをinstallする

//tscコマンドをinstall
$ npm i typescript -g
$ tsc --version
Version 4.6.2

//tsconfig.jsonを作成
$ tsc -init

Created a new tsconfig.json with:                                                                                       
                                                                                                                     TS 
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true


You can learn more at https://aka.ms/tsconfig.json
$ npm install --save-dev ts-jest @types/jest typescript
$ jest --init //jest.config.tsを作成

The following questions will help Jest to create a suitable configuration for your project

✔ Would you like to use Typescript for the configuration file? … yes
✔ Choose the test environment that will be used for testing › node
✔ Do you want Jest to add coverage reports? … no
✔ Which provider should be used to instrument code for coverage? › v8
✔ Automatically clear mock calls, instances and results before every test? … no

📝  Configuration file created at /Users/kin29/jest-test/jest.config.ts

$ vi jest.config.ts
- // transform: {}
+ transform: {
+   '.*\\.(ts)$' : '/node_modules/ts-jest',
+ },

TypeScriptでもテスト実行できるようになった〜🎉🎉🎉

$ npm test

> test
> jest

 PASS  ./sum.test.js
 PASS  ./ts-sum.test.ts

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.741 s
Ran all test suites.

さいごに

GASでテスト書きたいのでちょっと触ってみました!
次回はGAS+Jestでテスト書いた記事かければいいなーっと思っています💡

追記:書きましたー!!!

GASのテスト(Jest)を書く!!!

GASのユニットテストを書いてみる

お久しぶりです。
ネタが尽きてきたのと、サボってました…

名古屋にきて、名古屋飛ばしはあるものの
宮崎にいた時よりも行きたいアーティストのライブがありふれていて金欠の日々です。
(適度な副業あれば、ください^^)

 

今回の本題に入ります!

7月にテストをきちんと書いているとてもいい会社に転職しました。
フロントエンドでもきちんとテストに向き合っていて刺激的な毎日です。

そこで、わたしの大好きなGASでもテストかけないかなーってふいに思い、
ググってみると、、、、ある!!!

 

その名は、

\  QUnit for Google Apps Script  /

QUnit for Google Apps Script is an experimental fork of QUnit that enables developers to test their Google Apps Script code.

QUnitの実験的なGAS用ユニットテストのようです。
そもそも、QUnitを知らない不束者です…

 

使い方

参考:https://qiita.com/yooo_gooo/items/07c9513a87f6633e40c1

一. QUnitライブラリを追加

qunit/gas/README.md を参考にしてみます。

  1. Select “Resources” > “Manage Libraries…” in the Google Apps Script editor.
  2. Enter the project key (MxL38OxqIK-B73jyDTvCe-OBao7QLBR4j) in the “Find a Library” field, and choose “Select”.
  3. Select the highest version number, and choose QUnit as the identifier. (Do not turn on Development Mode unless you know what you are doing. The development version may not work.)
  4. Press Save. You can now use the QUnit library when writing your tests. You can see a list of available functions by typing QUnit followed by a dot. Alternatively, read the API docs.
  1. スクリプトエディタを開いて、リソース>ライブラリを選択する。
  2. ライブラリを追加の欄に、「MxL38OxqIK-B73jyDTvCe-OBao7QLBR4j」を入れて追加ボタンを押す
  3. QUnitの一番大きいバージョンを選択する。(詳しくない限り、デベロッッパーモードは有効にしない) ※今回はバージョン4を選びました。
  4. 保存ボタンを押下する。これでQunitライブラリを使えるようになりました。使用可能なQunit関数は API docs.を読んで。

QUniyライブラリの追加

 

 

二. テストを書く

README通り、 API docs.>QUnit (version 4) を参考にしました。

function doGet( e ) {
  QUnit.urlParams( e.parameter );
  QUnit.config({ title: "Unit tests for my project" });
  QUnit.load( isPublicHolidayTest );
  
  return QUnit.getHtml();
};

QUnit.helpers(this);

 

/**
 * テストコード
 */
function isPublicHolidayTest() {
  test('isPublicHoliday Test', function(assert) {
    var date = '2019-08-11';
    assert.ok(isPublicHoliday(new Date(date)), date +' は休日');

    var date = '2019-08-20';
    assert.ok(!isPublicHoliday(new Date(date)), date +' は休日ではない');

    var date = '2019-01-01';
    assert.ok(isPublicHoliday(new Date(date)), date +' は休日');
  });
}

 

/**
 * テスト対象の関数
 * (祝日であればtrue、そうでなければfalseを返す)
 */
function isPublicHoliday(data){
  //日本の祝日のカレンダーID
  var holidayCalId = "ja.japanese#holiday@group.v.calendar.google.com";
  var holidayCal = CalendarApp.getCalendarById(holidayCalId);

  return holidayCal.getEventsForDay(data).length > 0
}

 

▼assert.ok(value[, message])

を使ったことがなかったんですが、valueがtrueであれば「okay(message)」をechoするっぽいです。

assert.ok(true);                            //okay
assert.ok(true, 'okokok!!!');      //okokok!!!

参考:https://nodejs.org/api/assert.html#assert_assert_ok_value_message

 

 

三. テストを実行

スクリプトエディタの
公開 > ウェブアプリケーションとして導入 > 「最新のコードでテスト」のリンク
へ飛ぶとテストが実行され、結果がみれます。
※アプリケーションにアクセスできるユーザー:「自分だけ」にできます。

QUnitのテスト結果

 

 

感想

うーん、clasp使って、CIでテストさせたいですよねー
毎回、スクリプトエディタでテスト実行するのは面倒 😄

フロントのテストって書いたことがないのですが、
GASだったらセル依存となると思うので、テストを書くの難しそうだなあと感じました。。。