如何在 WebStorm 自訂 Jasmine Live Template?
WebStorm 雖然提供自動產生 Jasmine Suite、Spec… 等功能,不過預設使用 ES5 的 anonymous function,當然可以自己重構成 arrow function,若能一開始就 arrow function 就更方便了。
Version
WebStorm 2017.2
Symptons

WebStorm 內建提供了 4 個 Jasmine template,可使用熱鍵自動產生 Jasmine Suite、Jasmine Spec、Jasmine beforeEach 與 Jasmine afterEach。
Windows:Alt + Insert
macOS:⌘ + N

以 Jasmine Suite 為例,WebStorm 提供的 template 有 2 個缺點:
- suite name 使用單引號:但因為 suite 用來描述需求,因此可能再次使用單引號強調測試案例,若在單引號內使用雙引號,又變得不是很直接,因此希望 suite name 改用 backtick 寫法
- 使用 anonymous function:在 TypeScript 與 ES6 都習慣使用 arrow function 取代 anonymous function,語法較簡潔
Jasmine Spec 也有相同的問題。
此外對於常用的 expect(),WebStorm 也沒提供 template。
Recipes
我們將手動建立 3 個常用的 Jasmine live template,加速 ATDD 開發速度。
新增 Suite Template
1 | describe(``, () => { |

將我們想要的 suite template 先打好,選起來反白。

Tools -> Save as Live Template

- 輸入
des縮寫:將來只要輸入des,並按下tab,就會展開 suite template - 輸入 description:對
des加上Generate Jasmine Suite描述 user顯示des:user將顯示目前所有自訂的 live template- 游標預設停止處:在 backtick 內加入
$END$,則 live template 展開後,預設游標會停在此 - 儲存設定:按
OK儲存目前設定

輸入 des,在 Intellisense 也找到了,並且顯示 Generate Jasmine Suite 描述。

輸入 des 按下 tab 後,會自動展開剛剛建立的 live template,並將游標停在 suite name 之處。
新增 Spec Template
1 | it(``, () => { |

將我們想要的 spec template 先打好,選起來反白。

Tools -> Save as Live Template

- 輸入
it縮寫:將來只要輸入it,並按下tab,就會展開 spec template - 輸入 description:對
it加上Generate Jasmine Spec描述 user顯示it:user將顯示目前所有自訂的 live template- 游標預設停止處:在 backtick 內加入
$END$,則 live template 展開後,預設游標會停在此 - 儲存設定:按
OK儲存目前設定

輸入 it,在 Intellisense 也找到了,並且顯示 Generate Jasmine Spec 描述。

輸入 it 按下 tab 後,會自動展開剛剛建立的 live template,並將游標停在 spec name 之處。
新增 Expect Template
1 | expect().toBe(); |

將我們想要的 expect template 先打好,選起來反白。

Tools -> Save as Live Template

- 輸入
exp縮寫:將來只要輸入exp,並按下tab,就會展開 expect template - 輸入 description:對
exp加上Generate Jasmine Expect描述 user顯示exp:user將顯示目前所有自訂的 live template- 游標預設停止處:在 backtick 內加入
$END$,則 live template 展開後,預設游標會停在此 - 儲存設定:按
OK儲存目前設定

輸入 exp,在 Intellisense 也找到了,並且顯示 Generate Jasmine Expect 描述。

輸入 exp 按下 tab 後,會自動展開剛剛建立的 live template,並將游標停在 expect() 之內。
Conclusion
Save as Live Template是 JetBrains IntelliJ 平台都有的功能,在 PhpStorm、WebStorm 與 Rider 都可使用,可自行將常用的 code snippet 存下來,增加開發效率。