
- JasmineJS 教程
- JasmineJS - 首頁
- JasmineJS - 概述
- JasmineJS - 環境設定
- JasmineJS - 書寫測試用例及執行
- JasmineJS - BDD 架構
- JasmineJS - 測試的構建塊
- JasmineJS - 匹配器
- JasmineJS - 跳過塊
- JasmineJS - 等值檢查
- JasmineJS - 布林值檢查
- JasmineJS - 順序檢查
- JasmineJS - 空值檢查
- JasmineJS - 不等值檢查
- JasmineJS - 非數字檢查
- JasmineJS - 異常檢查
- JasmineJS - beforeEach()
- JasmineJS - afterEach()
- JasmineJS - 間諜 (Spies)
- JasmineJS 有用資源
- JasmineJS - 快速指南
- JasmineJS - 有用資源
- JasmineJS - 討論
JasmineJS - 順序檢查
Jasmine 還提供不同的方法來實現 JS 輸出的順序性。以下示例展示瞭如何使用 Jasmine 實現順序檢查。
toContain()
toContain() 匹配器允許我們檢查任何元素是否屬於同一個陣列或其他順序物件的一部分。以下示例將幫助我們瞭解 Jasmine toContain() 方法的工作機制。讓我們在之前建立的 customerMatcherSpec.js 檔案中新增以下程式碼。
describe("Different Methods of Expect Block",function () { it("The Example of toContain() method",function () { expect([1,2, 3, 4]).toContain(3); }); });
在上面的示例中,我們正在檢查 3 是否存在於該陣列中。由於 3 存在於陣列中,我們得到綠色輸出。

在上面的示例中,讓我們將 3 的值更改為 15 並再次執行規範。由於 15 不屬於我們作為該函式引數傳遞的陣列,我們將看到紅色螢幕。

toBeCloseTo()
toBeCloseTo() 匹配器匹配實際值是否接近預期值。在下面的示例中,我們將修改 customerMatcherSpec.js 檔案,看看它實際上是如何工作的。
describe("Different Methods of Expect Block", function () { it("Example of toBeCloseTo()", function () { expect(12.34).toBeCloseTo(12.3, 1); }); });
在上面的 Describe 塊中,我們正在檢查實際結果“12.3”是否接近預期輸出“12.34”。由於這滿足了我們的要求,我們將得到綠色截圖作為輸出。此方法的第二個引數是要比較的小數位數。

在上面的程式碼中,讓我們將預期值修改為 15 並執行 SpecRunner.html。
describe("Different Methods of Expect Block",function () { it("Example of toBeCloseTo()", function () { expect(12.34).toBeCloseTo(15, 1); }); });
在這種情況下,15 與 15 根本不接近,因此它將生成錯誤並顯示紅色截圖作為錯誤。

toMatch()
toMatch() 匹配器用於字串型別變數。它有助於查詢特定字串是否存在於預期輸出中。以下是我們的 customerMatcherSpec.js 檔案的樣子。
describe("Different Methods of Expect Block",function () { it("Example of toMatch()", function () { expect("Jasmine tutorial in tutorials.com").toMatch(/com/); }); });
這段程式碼將測試給定的預期字串中是否存在 “com”。由於 com 存在於字串中,它將生成綠色截圖並透過測試條件。

現在讓我們將輸出更改為預期值中不存在的其他字串。然後我們的 customerMatcherSpec.js 將如下所示。
describe("Different Methods of Expect Block",function () { it("Example of toMatch()", function () { expect("Jasmine tutorial in tutorials.com").toMatch(/XYZ/); }); });
上面的程式碼將在預期值中查詢“XYZ”字串。由於它不存在於預期字串中,它將丟擲錯誤,並且輸出螢幕將相應地顯示紅色。
