<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Jasmine 單元測試教程及示例 > 原文: [https://howtodoinjava.com/javascript/jasmine-unit-testing-tutorial/](https://howtodoinjava.com/javascript/jasmine-unit-testing-tutorial/) **Jasmine** 是流行的 JavaScript 單元測試框架之一,能夠測試同步和異步 JavaScript 代碼。 它用于 BDD(行為驅動的開發)編程中,該編程更多地側重于業務價值而不是技術細節。 在此 **Jasmine 教程**中,我們將從設置說明到了解測試用例的輸出來詳細學習 Jasmine 框架。 ```java Table of Contents 1\. Jasmine Setup Configuration 2\. Writing Suite and Specs 3\. Setup and Teardown 4\. Jasmine Describe Blocks 5\. Jasmine Matchers 6\. Disable Suites and Specs 7\. Working with Jasmine Spy 8\. Final Thoughts ``` ## 1\. Jasmine 起步配置 首先[下載 Jasmine 框架](https://github.com/jasmine/jasmine/releases)并將其解壓縮到您的項目文件夾中。 我建議在應用中可能已經存在的`/js`或`/javascript`文件夾下創建一個單獨的文件夾`/jasmine`。 您將在分發捆綁包中獲得以下四個文件夾/文件: 1. `/src`:包含您要測試的 JavaScript 源文件 2. `/lib`:包含框架文件 3. `/spec`:包含 JavaScript 測試文件 4. `SpecRunner.html`:是測試用例運行器 HTML 文件 您可以刪除`/src`文件夾; 并從`SpecRunner.html`文件中的當前位置引用源文件。 默認文件如下所示,您將需要更改`/src`和`/spec`文件夾中包含的文件。 ```java <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Jasmine Spec Runner v2.4.1</title> <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png"> <link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css"> <script src="lib/jasmine-2.4.1/jasmine.js"></script> <script src="lib/jasmine-2.4.1/jasmine-html.js"></script> <script src="lib/jasmine-2.4.1/boot.js"></script> <!-- include source files here... --> <script src="src/Player.js"></script> <script src="src/Song.js"></script> <!-- include spec files here... --> <script src="spec/SpecHelper.js"></script> <script src="spec/PlayerSpec.js"></script> </head> <body></body> </html> ``` 在此演示中,我刪除了`/src`文件夾,并將引用其當前位置的文件。 當前的文件夾結構如下: ![Jasmine Folder Structure](https://img.kancloud.cn/72/7b/727bb970975c0bed3ee9cb2cb2168184_276x364.png) Jasmine 文件夾結構 為了專注于 Jasmine 的功能,我將創建一個具有一些基本操作的簡單 JS 文件`MathUtils.js`,我們將對這些功能進行單元測試。 ```java MathUtils = function() {}; MathUtils.prototype.sum = function(number1, number2) { return number1 + number2; } MathUtils.prototype.substract = function(number1, number2) { return number1 - number2; } MathUtils.prototype.multiply = function(number1, number2) { return number1 * number2; } MathUtils.prototype.divide = function(number1, number2) { return number1 / number2; } MathUtils.prototype.average = function(number1, number2) { return (number1 + number2) / 2; } MathUtils.prototype.factorial = function(number) { if (number < 0) { throw new Error("There is no factorial for negative numbers"); } else if (number == 1 || number == 0) { return 1; } else { return number * this.factorial(number - 1); } } ``` 在`SpecRunner.html`中添加文件引用后,文件內容將為: ```java <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Jasmine Spec Runner v2.4.1</title> <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png"> <link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css"> <script src="lib/jasmine-2.4.1/jasmine.js"></script> <script src="lib/jasmine-2.4.1/jasmine-html.js"></script> <script src="lib/jasmine-2.4.1/boot.js"></script> <!-- include source files here... --> <script src="../MathUtils.js"></script> <!-- include spec files here... --> <script src="spec/MathUtils.js"></script> </head> <body></body> </html> ``` ## 2\. Jasmine 套件和規范 在 Jasmine 中,有兩個重要術語 – **套件**和**規范**。 #### 2.1 套件 Jasmine 套件是一組測試用例,可用于測試 JavaScript 代碼(JavaScript 對象或函數)的特定行為。 首先使用兩個參數調用 Jasmine 全局函數`describe` - 第一個參數代表測試套件的標題,第二個參數代表實現測試套件的功能。 ```java //This is test suite describe("Test Suite", function() { //..... }); ``` #### 2.2 規范 Jasmine 規范表示測試套件中的一個測試用例。 首先使用兩個參數調用 Jasmine 全局函數`it` - 第一個參數代表規范的標題,第二個參數代表實現測試用例的函數。 實際上,規范包含一個或多個期望。 每個期望代表一個可以為`true`或`false`的斷言。 為了通過規范,規范內的所有期望都必須為`true`。 如果規范中的一個或多個期望是`false`,則規范失敗。 ```java //This is test suite describe("Test Suite", function() { it("test spec", function() { expect( expression ).toEqual(true); }); }); ``` 讓我們開始為`MathUtils.js`編寫單元測試,以更好地了解套件和規范。 我們將在`spec/MathUtils.js`中編寫這些規范。 ```java describe("MathUtils", function() { var calc; //This will be called before running each spec beforeEach(function() { calc = new MathUtils(); }); describe("when calc is used to peform basic math operations", function(){ //Spec for sum operation it("should be able to calculate sum of 3 and 5", function() { expect(calc.sum(3,5)).toEqual(8); }); //Spec for multiply operation it("should be able to multiply 10 and 40", function() { expect(calc.multiply(10, 40)).toEqual(400); }); //Spec for factorial operation for positive number it("should be able to calculate factorial of 9", function() { expect(calc.factorial(9)).toEqual(362880); }); //Spec for factorial operation for negative number it("should be able to throw error in factorial operation when the number is negative", function() { expect(function() { calc.factorial(-7) }).toThrowError(Error); }); }); }); ``` 在瀏覽器中打開`SpecRunner.html`文件時,將運行規范并在瀏覽器中呈現結果,如下所示: ![Jasmine Output](https://img.kancloud.cn/27/cf/27cfadffaccad52f677288fad93a9450_648x219.png) Jasmine 輸出 ## 3\. 安裝和拆卸 為了進行安裝和拆卸,Jasmine 在套件級別提供了兩個全局函數,即`beforeEach()`和`afterEach()`。 #### 3.1 `beforeEach()` 在調用`describe()`的每個規范之前,會先調用`beforeEach`函數。 #### 3.2 `afterEach()` 每個規范后都會調用一次`afterEach`函數。 實際上,規范變量(任何變量)在頂級范圍`describe`塊中定義,并且初始化代碼被移到`beforeEach`函數中。 `afterEach`函數在繼續之前重置變量。 這有助于開發人員不要為每個規范重復設置和完成代碼。 ## 4\. Jasmine 描述塊 在 Jasmine 中,`describe`函數用于對相關規范進行分組。 字符串參數用于命名規范集合,并將其與規范連接在一起以形成規范的全名。 這有助于在大型套件中查找規范。 好消息是,您也可以嵌套`describe`塊。 在嵌套`describe`的情況下,Jasmine 在執行規范之前先按順序執行每個`beforeEach`函數,然后執行規范,最后逐步執行每個`afterEach`函數。 讓我們通過一個例子來理解它。 將`MathUtilSpecs.js`中的內容替換為以下代碼: ```java describe("Nested Describe Demo", function() { beforeEach(function() { console.log("beforeEach level 1"); }); describe("MyTest level2", function() { beforeEach(function() { console.log("beforeEach level 2"); }); describe("MyTest level3", function() { beforeEach(function() { console.log("beforeEach level 3"); }); it("is a simple spec in level3", function() { console.log("A simple spec in level 3"); expect(true).toBe(true); }); afterEach(function() { console.log("afterEach level 3"); }); }); afterEach(function() { console.log("afterEach level 2"); }); }); afterEach(function() { console.log("afterEach level 1"); }); }); ``` 現在,通過在瀏覽器中打開`SpecRunner.html`執行此文件。 觀察控制臺輸出,它寫為: ```java beforeEach level 1 beforeEach level 2 beforeEach level 3 A simple spec in level 3 afterEach level 3 afterEach level 2 afterEach level 1 ``` 我建議您在上面的代碼中放置更多規范,并查看執行流程以更好地理解。 ## 5\. Jasmine 匹配器 在第一個示例中,我們看到了`toEqual`和`toThrow`函數的用法。 它們是匹配器,用于比較任何 Jasmine 測試的實際輸出和預期輸出。 您就像 Java 斷言一樣,如果有幫助的話。 讓我們列出所有這些 Jasmine 匹配器,它們可以幫助您制定更強大,更有意義的測試規范。 | 匹配器 | 目的 | | --- | --- | | `toBe()` | 如果實際值與期望值的類型和值相同,則通過。 它與`===`運算符進行比較 | | `toEqual()` | 適用于簡單的文字和變量;也應適用于對象 | | `toMatch()` | 檢查值是否匹配字符串或正則表達式 | | `toBeDefined()` | 確保定義了屬性或值 | | `toBeUndefined()` | 確保未定義屬性或值 | | `toBeNull()` | 確保屬性或值為空。 | | `toBeTruthy()` | 確保屬性或值是`true` | | `toBeFalsy()` | 確保屬性或值是`false` | | `toContain()` | 檢查字符串或數組是否包含子字符串或項目。 | | `toBeLessThan()` | 用于小于的數學比較 | | `toBeGreaterThan()` | 用于大于的數學比較 | | `toBeCloseTo()` | 用于精確數學比較 | | `toThrow()` | 用于測試函數是否引發異常 | | `toThrowError()` | 用于測試引發的特定異常 | Jasmine `not`關鍵字可以與每個匹配器的條件一起使用,以求將結果取反。 例如: ```java expect(actual).not.toBe(expected); expect(actual).not.toBeDefined(expected); ``` ## 6\. 禁用套件和規范 很多時候,出于各種原因,您可能需要禁用套件 - 一段時間。 在這種情況下,您無需刪除代碼 - 只需在`describe`的開頭添加`char x`以使`if`為`xdescribe`。 這些套件及其內部的任何規范在運行時都會被跳過,因此其結果將不會出現在結果中。 ```java xdescribe("MathUtils", function() { //code }); ``` 如果您不想禁用整個套件,而是只想禁用某個規范測試,然后將`x`放在該規范本身之前,這一次將僅跳過該規范。 ```java describe("MathUtils", function() { //Spec for sum operation xit("should be able to calculate the sum of two numbers", function() { expect(10).toBeSumOf(7, 3); }); }); ``` ## 7\. 與 Jasmine 間諜一起工作 Jasmine 具有雙重測試功能,稱為間諜。間諜可以對任何函數進行存根,并跟蹤對該函數和所有參數的調用。 間諜僅存在于定義它的`describe`或`it`塊中,并且在每個規范后都會被刪除。 要使用任何方法創建間諜,請使用`spyOn(object, 'methodName')`調用。 有兩個匹配器`toHaveBeenCalled`和`toHaveBeenCalledWith`應該與間諜一起使用。 如果調用了間諜,則`toHaveBeenCalled`匹配器將返回`true`;否則,將返回`true`。 如果參數列表與對間諜的任何記錄調用匹配,則`toHaveBeenCalledWith`匹配器將返回`true`。 ```java describe("MathUtils", function() { var calc; beforeEach(function() { calc = new MathUtils(); spyOn(calc, 'sum'); }); describe("when calc is used to peform basic math operations", function(){ //Test for sum operation it("should be able to calculate sum of 3 and 5", function() { //call any method calc.sum(3,5); //verify it got executed expect(calc.sum).toHaveBeenCalled(); expect(calc.sum).toHaveBeenCalledWith(3,5); }); }); }); ``` 上面的示例本質上是最基本的,您也可以使用間諜來驗證對內部方法的調用。 例如。 如果在任何對象上調用方法`calculateInterest()`,則可能需要檢查是否必須在該對象內調用`getPrincipal()`,`getROI()`和`getTime()`。 間諜將幫助您驗證這些假設。 當沒有要監視的函數時,`jasmine.createSpy`可以創建裸露的間諜。 該間諜的行為與其他任何間諜一樣 - 跟蹤調用,參數等。但是它背后沒有實現。 間諜是 JavaScript 對象,可以這樣使用。 通常,這些間諜在需要時用作其他函數的回調函數。 ```java var callback = jasmine.createSpy('callback'); //Use it for testing expect(object.callback).toHaveBeenCalled(); ``` 如果需要定義多個此類方法,則可以使用快捷方式`jasmine.createSpyObj`。 例如: ```java tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); tape.play(); //Use it for testing expect(tape.play.calls.any()).toEqual(true); ``` 在`calls`屬性上跟蹤并公開了對間諜的每次調用。 讓我們看看如何使用這些屬性來跟蹤間諜。 | 追蹤屬性 | 目的 | | --- | --- | | `.calls.any()` | 如果根本沒有調用過該間諜,則返回`false`;如果至少發生一次調用,則返回`true`。 | | `.calls.count()` | 返回間諜被調用的次數 | | `.calls.argsFor(index)` | 返回傳遞給電話號碼索引的參數 | | `.calls.allArgs()` | 返回所有調用的參數 | | `.calls.all()` | 返回上下文(`this`),并且參數傳遞了所有調用 | | `.calls.mostRecent()` | 返回上下文(`this`)和最近一次調用的參數 | | `.calls.first()` | 返回第一次調用的上下文(`this`)和參數 | | `.calls.reset()` | 清除所有跟蹤以發現間諜 | ## 8\. Jasmine 教程 – 最終想法 Jasmine 是用于測試 javascript 函數的非常強大的框架,但是學習曲線有點困難。 在使用 Jasmine 進行有效測試之前,需要編寫大量實際的 javascript 代碼。 請記住,Jasmine 旨在用于以 [BDD](https://en.wikipedia.org/wiki/Behavior-driven_development)(行為驅動的開發)樣式編寫測試。 不要通過測試無關的東西來濫用它。 讓我知道您對本**初學者 Jasmine 教程**的想法。 學習愉快! 參考文獻: [Jasmine Github 倉庫](https://github.com/jasmine/jasmine)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看