<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>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Jest 教程 > 標題: [http://zetcode.com/javascript/jest/](http://zetcode.com/javascript/jest/) Jest 教程展示了如何使用 Jest 框架在 JavaScript 應用中執行單元測試。 ## Jest Jest JavaScript REST 框架,其重點是簡單性。 Jest 是由 Facebook 工程師為其 React 項目創建的。 單元測試是一種軟件測試,其中測試軟件的各個單元(組件)。 單元測試的目的是驗證軟件的每個單元是否按設計執行。 單元是所有軟件中最小的可測試部分。 模擬是一種技術,其中代碼部分被模擬真實代碼的虛擬實現所替代。 模擬有助于實現測試隔離。 模擬主要用于單元測試。 在我們的測試中,我們檢查值是否滿足某些條件。 `expect()`函數為我們提供了許多匹配器,這些匹配器使我們可以驗證不同的事物,例如`toBe()`,`toBeFalsy()`或`toEqual()`。 在本教程中,我們在 Node 應用中使用 Jest。 ## 安裝 Jest 首先,我們安裝 Jest。 ```js $ node -v v11.5.0 ``` 我們使用 Node 版本 11.5.0。 ```js $ npm init -y ``` 我們啟動一個新的 Node 應用。 ```js $ npm i --dev jest ``` 我們用`nmp i --dev jest`安裝 Jest 模塊。 ```js $ npm i -g jsonserver $ npm i axios ``` 我們也將使用`jsonserver`和`axios`。 ## package.json 測試腳本運行`jest`。 `package.json` ```js { "name": "jest-test", "version": "1.0.0", "description": "", "main": "main.js", "scripts": { "test": "jest --verbose" }, "keywords": [], "author": "Jan Bodnar", "license": "ISC", "devDependencies": { "jest": "^24.0.0" }, "dependencies": { "axios": "^0.18.0" } } ``` 缺省情況下,笑話僅提供基本輸出。 要獲得有關測試運行的更多信息,我們使用`--verbose`標志。 ## Jest 運行測試 使用`npm test`命令運行測試。 測試文件的名稱中必須帶有`test`術語。 ```js $ npm test > jest-test@1.0.0 test C:\Users\Jano\Documents\js\jest-test > jest PASS ./math-utils.test.js PASS ./arith.test.js PASS ./arith-params.test.js PASS ./arith-skip.test.js PASS ./string-utils.test.js PASS ./arith-mock.test.js PASS ./users.test.js Test Suites: 7 passed, 7 total Tests: 2 skipped, 35 passed, 37 total Snapshots: 0 total Time: 5.19s Ran all test suites. ``` 這是使用 Jest 運行測試的示例輸出。 這是一個簡潔的輸出。 有關更多信息,我們可以使用`--verbose`選項。 要運行單個測試,我們可以使用`npx jest testname`命令。 ```js scripts:{ "test": "jest --verbose ./test-directory" } ``` 我們可以配置 Jest 在指定的測試目錄中運行測試。 ## 用 Jest 測試算術函數 以下是使用 Jest 降級單元測試的經典學術示例。 `arith.js` ```js const add = (a, b) => a + b; const mul = (a, b) => a * b; const sub = (a, b) => a - b; const div = (a, b) => a / b; module.exports = { add, mul, sub, div }; ``` 一個模塊中有四個基本算術函數。 `arith.test.js` ```js const { add, mul, sub, div } = require('./arith'); test('2 + 3 = 5', () => { expect(add(2, 3)).toBe(5); }); test('3 * 4 = 12', () => { expect(mul(3, 4)).toBe(12); }); test('5 - 6 = -1', () => { expect(sub(5, 6)).toBe(-1); }); test('8 / 4 = 2', () => { expect(div(8, 4)).toBe(2); }); ``` 在`arith.test.js`中,我們測試模塊。 文件名包含測試詞。 然后由玩笑挑出來。 ```js test('2 + 3 = 5', () => { expect(add(2, 3)).toBe(5); }); ``` 我們使用`test()`函數測試`add()`方法。 第一個參數是測試的名稱,第二個參數是要運行的函數。 我們正在測試`add()`函數返回的樣本數據正確答案。 ```js $ npx jest arith.test.js PASS ./arith.test.js √ 2 + 3 = 5 (3ms) √ 3 * 4 = 12 (6ms) √ 5 - 6 = -1 √ 8 / 4 = 2 (1ms) Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total Snapshots: 0 total Time: 10.981s Ran all test suites matching /arith.test.js/i. ``` 這是輸出。 ## Jest 跳過測試 測試可能需要花費大量時間才能完成。 如果需要,我們可以跳過一些測試。 `arith-skip.test.js` ```js const { add, mul, sub, div } = require('./arith'); xtest('2 + 3 = 5', () => { expect(add(2, 3)).toBe(5); }); test.skip('3 * 4 = 12', () => { expect(mul(3, 4)).toBe(12); }); test('5 - 6 = -1', () => { expect(sub(5, 6)).toBe(-1); }); test('8 / 4 = 2', () => { expect(div(8, 4)).toBe(2); }); ``` 可以使用`skip()`或使用`x`前綴跳過測試。 在我們的例子中,前兩個測試被跳過。 ```js $ npx jest arith-skip.test.js PASS ./arith-skip.test.js √ 5 - 6 = -1 (2ms) √ 8 / 4 = 2 (1ms) ○ skipped 2 tests Test Suites: 1 passed, 1 total Tests: 2 skipped, 2 passed, 4 total Snapshots: 0 total Time: 2.323s Ran all test suites matching /arith-skip.test.js/i. ``` 跳過了兩個測試。 ## Jest 參數化測試 參數化測試允許我們使用不同的值多次運行相同的測試。 這使我們的測試功能更強大。 對于參數化測試,我們使用`each()`全局函數。 `arith-param.test.js` ```js const { add, mul, sub, div } = require('./arith') test.each([[1, 1, 2], [-1, 2, 1], [2, 1, 3]])( '%i + %i equals %i', (a, b, expected) => { expect(add(a, b)).toBe(expected); }, ); test.each([[1, 1, 0], [-1, 2, -3], [2, 2, 0]])( '%i - %i equals %i', (a, b, expected) => { expect(sub(a, b)).toBe(expected); }, ); test.each([[1, 1, 1], [-1, 2, -2], [2, 2, 4]])( '%i * %i equals %i', (a, b, expected) => { expect(mul(a, b)).toBe(expected); }, ); test.each([[1, 1, 1], [-1, 2, -0.5], [2, 2, 1]])( '%i / %i equals %i', (a, b, expected) => { expect(div(a, b)).toBe(expected); }, ); ``` 在這些測試中,我們使用不同的輸入數據多次運行每個算術函數。 ```js test.each([[1, 1, 2], [-1, 2, 1], [2, 1, 3]])( '%i + %i equals %i', (a, b, expected) => { expect(add(a, b)).toBe(expected); }, ); ``` `each()`方法接收一個數組數組,該數組的參數將傳遞給每一行的測試函數。 `%i`是需要整數的格式說明符。 這是針對`--verbose`選項顯示的輸出的。 ```js $ npx jest arith-params.test.js PASS ./arith-params.test.js √ 1 + 1 equals 2 (3ms) √ -1 + 2 equals 1 (1ms) √ 2 + 1 equals 3 √ 1 - 1 equals 0 √ -1 - 2 equals -3 √ 2 - 2 equals 0 √ 1 * 1 equals 1 (1ms) √ -1 * 2 equals -2 √ 2 * 2 equals 4 √ 1 / 1 equals 1 (1ms) √ -1 / 2 equals 0 √ 2 / 2 equals 1 Test Suites: 1 passed, 1 total Tests: 12 passed, 12 total Snapshots: 0 total Time: 1.759s Ran all test suites matching /arith-params.test.js/i. ``` 這是輸出。 ## Jest `beforeAll()`函數是測試設置的一部分。 它會在運行此文件中的任何測試之前運行一個函數。 如果函數返回一個`Promise`或是一個生成器,則 Jest 在運行測試之前等待該`Promise`解析。 `math-utils.js` ```js const sum = (vals) => { let sum = 0; vals.forEach((val) => { sum += val; }); return sum; } const positive = (vals) => { return vals.filter((x) => { return x > 0; }); } const negative = (vals) => { return vals.filter((x) => { return x < 0; }); } module.exports = { sum, positive, negative }; ``` 我們有一個`math-utils`模塊,其中包含三個函數:`sum()`,`positive()`和`negative()`。 `math-utils.test.js` ```js const { sum, positive, negative } = require('./math-utils'); let vals; let sum_of_vals; let pos_vals; let neg_vals; beforeAll(() => { pos_vals = [2, 1, 3]; neg_vals = [-2, -1, -1]; vals = pos_vals.concat(neg_vals); sum_of_vals = vals.reduce((x, y) => x + y, 0); }) test('the sum of vals should be 2', () => { expect(sum(vals)).toBe(sum_of_vals); }); test('should get positive values', () => { expect(positive(vals)).toEqual(pos_vals); }); test('should get negative values', () => { expect(negative(vals)).toEqual(neg_vals); }); ``` 在測試文件中,我們使用`beforeAll()`函數的測試運行之前初始化測試數據。 ```js test('should get positive values', () => { expect(positive(vals)).toEqual(pos_vals); }); ``` 為了測試`positive()`函數,我們使用`toEqual()`匹配器。 我們測試該函數返回的正值數組等于預定義的測試值數組。 ## Jest 分組測試 在 Jest 中,測試使用`describe()`分組為單位。 它創建一個將幾個相關測試組合在一起的模塊。 `string-utils.js` ```js const isPalindrome = (string) => string == string.split('').reverse().join(''); const isAnagram = (w1, w2) => { const regularize = (word) => { return word.toLowerCase().split('').sort().join('').trim(); } return regularize(w1) === regularize(w2); } module.exports = {isPalindrome, isAnagram}; ``` 我們的`string-utils.js`模塊具有兩個函數:`isPalindrome()`和`isAnagram()`。 `math-utils.js` ```js const sum = (vals) => { let sum = 0; vals.forEach((val) => { sum += val; }); return sum; } const positive = (vals) => { return vals.filter((x) => { return x > 0; }); } const negative = (vals) => { return vals.filter((x) => { return x < 0; }); } module.exports = { sum, positive, negative }; ``` 我們又有了`math-utils.js`模塊。 `groups.test.js` ```js const { sum, positive, negative } = require('./math-utils'); const { isPalindrome, isAnagram } = require('./string-utils'); describe('testing math utilities', () => { let vals; let sum_of_vals; let pos_vals; let neg_vals; beforeAll(() => { pos_vals = [2, 1, 3]; neg_vals = [-2, -1, -1]; vals = pos_vals.concat(neg_vals); sum_of_vals = vals.reduce((x, y) => x + y, 0); }) test('the sum of vals should be 2', () => { expect(sum(vals)).toBe(sum_of_vals); }); test('should get positive values', () => { expect(positive(vals)).toEqual(pos_vals); }); test('should get negative values', () => { expect(negative(vals)).toEqual(neg_vals); }); }); describe('testing string utilities', () => { test.each(["racecar", "radar", "level", "refer", "deified", "civic"])( 'testing %s for palindrome', (word) => { expect(isPalindrome(word)).toBeTruthy(); }, ); test.each([["arc", "car"], ["cat", "act"], ["cider", "cried"]])( 'testing if %s and %s are anagrams ', (word1, word2) => { expect(isAnagram(word1, word2)).toBeTruthy(); }, ); }); ``` 使用`describe()`,我們為字符串和數學工具創建了兩個獨立的測試組。 例如,`beforeAll()`僅適用于數學工具。 ```js $ npx jest groups.test.js PASS ./groups.test.js testing math utilities √ the sum of vals should be 2 (3ms) √ should get positive values (1ms) √ should get negative values testing string utilities √ testing racecar for palindrome (1ms) √ testing radar for palindrome √ testing level for palindrome √ testing refer for palindrome √ testing deified for palindrome (1ms) √ testing civic for palindrome √ testing if arc and car are anagrams √ testing if cat and act are anagrams √ testing if cider and cried are anagrams (1ms) Test Suites: 1 passed, 1 total Tests: 12 passed, 12 total Snapshots: 0 total Time: 1.786s Ran all test suites matching /groups.test.js/i. ``` 我們運行測試。 ## Jest 測試 Axios 在以下部分中,我們將測試使用 Axios 庫的 JavaScript 代碼。 首先,我們安裝了`axios`和`json-server`模塊。 `users.json` ```js { "users": [ { "id": 1, "first_name": "Robert", "last_name": "Schwartz", "email": "rob23@gmail.com" }, { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "lucyb56@gmail.com" }, { "id": 3, "first_name": "Anna", "last_name": "Smith", "email": "annasmith23@gmail.com" }, { "id": 4, "first_name": "Robert", "last_name": "Brown", "email": "bobbrown432@yahoo.com" }, { "id": 5, "first_name": "Roger", "last_name": "Bacon", "email": "rogerbacon12@yahoo.com" } ] } ``` 這是 JSON 服務器的一些偽造數據。 `users.js` ```js const axios = require('axios'); class Users { static async all() { let res = await axios.get('http://localhost:3000/users'); return res; } } module.exports = Users; ``` `users.js`模塊使用`axios`檢索數據。 我們將測試該模塊。 `users-app.js` ```js const Users = require('./users'); async function showData() { let res = await Users.all(); console.log(res.data); } showData(); console.log('finished') ``` `users-app.js`是使用`users.js`模塊獲取和輸出數據的應用。 ```js $ json-server --watch users.json ``` 我們開始`json-server`。 ```js $ node users-app.js finished [ { id: 1, first_name: 'Robert', last_name: 'Schwartz', email: 'rob23@gmail.com' }, { id: 2, first_name: 'Lucy', last_name: 'Ballmer', email: 'lucyb56@gmail.com' }, { id: 3, first_name: 'Anna', last_name: 'Smith', email: 'annasmith23@gmail.com' }, { id: 4, first_name: 'Robert', last_name: 'Brown', email: 'bobbrown432@yahoo.com' }, { id: 5, first_name: 'Roger', last_name: 'Bacon', email: 'rogerbacon12@yahoo.com' } ] ``` 我們運行該應用。 `users.test.js` ```js const axios = require('axios'); const Users = require('./users'); jest.mock('axios'); test('should fetch users', () => { const users = [{ "id": 1, "first_name": "Robert", "last_name": "Schwartz", "email": "rob23@gmail.com" }, { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "lucyb56@gmail.com" }]; const resp = { data : users }; axios.get.mockImplementation(() => Promise.resolve(resp)); Users.all().then(resp => expect(resp.data).toEqual(users)); }); ``` 該測試文件測試`users.js`模塊。 ```js jest.mock('axios'); ``` 我們模擬模塊。 ```js const users = [{ "id": 1, "first_name": "Robert", "last_name": "Schwartz", "email": "rob23@gmail.com" }, { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "lucyb56@gmail.com" }]; const resp = { data : users }; ``` 這是模擬模塊將返回的響應。 ```js axios.get.mockImplementation(() => Promise.resolve(resp)); ``` 模擬實現返回帶有響應的`promise`。 ```js Users.all().then(resp => expect(resp.data).toEqual(users)); ``` 我們測試了模擬的`Users.all()`函數。 ```js $ npx jest users.test.js PASS ./users.test.js √ should fetch users (4ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.818s Ran all test suites matching /users.test.js/i. ``` 我們進行測試。 在本教程中,我們使用 Jest 在 JavaScript 應用中進行單元測試。 您可能也對以下相關教程感興趣: [Moment.js 教程](/javascript/momentjs/), [Axios 教程](/javascript/axios/), [Faker.js 教程](/javascript/faker), [JSONServer 教程](/javascript/jsonserver/) ,[從 JavaScript 中的 URL 讀取 JSON](/articles/javascriptjsonurl/) , [Node Sass 教程](/javascript/nodesass/), [Lodash 教程](/javascript/lodash/)。
                  <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>

                              哎呀哎呀视频在线观看