過去我曾在文章「Jasmine 測試當中建立假物件的小技巧」介紹 Jasmine.Spy 系列方法,提到 Spy 可以幫助提高測試的「靈活度」與「可測性」,這樣的說法是基於 Spy 擁有「改變結果」與「觀察」的能力。
Jasmine.Spy
本文記錄透過 Jasmine 撰寫單元測試時,如何進行一反向的驗證,例如「不等於」某個值、「不要執行」某個行為的測試場景,並簡單描述「延遲驗證」的使用案例。
這兩個名詞時常混淆,摘錄在 Stake overflow 看到的簡潔說明 (Ref.)。
A stub is a simple fake object. It just makes sure test runs smoothly.A mock is a smarter stub. You verify your test passes through it.
Angular 預設使用 Jasmine 測試框架,撰寫測試時應常接觸 Spy 系列方法,本文提供一些小技巧,讓您撰寫與維護測試時更為方便。
這裡以假物件來代稱,你可能在他處看到 Test doubble (測試替身) 的字眼,或聽到較口語的 Mock 說法,這邊就泛指這些東西。(註:Mock 與 Stub 有些區別,未來再寫文章說明)