[JS102] Jest


Posted by yymarlerr on 2021-05-15

Jest

  • 現成的測試 framework
  • 安裝

流程

  1. 先把功能 exports 出來:module.exports = <想要 export 的功能>
  • 範例:

    function double(a) {
      return a*2
    }
    
    module.exports = double
    
  1. 新增另一個檔案叫testing.test.js,並 import 該 module,並輸入以下:
    test('<描述>', function() { expect(<想要測試的東西>).toBe(<正確的值>);
    • function 為要測試的東西
    • function 也可以放在 test 的外面
  • 舉例:

    var needDouble = require('./mymodule')
    
    test('測試看看是不是會變成兩倍', function( {
    expect(needDouble(4)).toBe(8)
    });
    
  • 單元測試,用 Describe('<描述>', function() {放 test....那大串} )

var needDouble = require('./mymodule')

describle('測試看看是不是會變成兩倍', function() {
  test('測試看看 4 是不是會變成 8', function() {
    expect(needDouble(4)).toBe(8)
  });
  test('測試看看 5 是不是會變成 10', function() {
    expect(needDouble(5)).toBe(10)
  });
})
  1. 更新 package.json:

    "scripts": {
      "test": "jest"
    }
    
  2. 去 terminal 輸入 npm run test

    • 會去找副檔名是 test.js 的檔案
    • 沒辦法直接在 terminal 輸入 jest 的原因是,jest 只有 under 在這個 project,如果沒有加 npm 的會,會變成是去系統找 jest,結果就找不到。

其他狀況:

  1. 如果只想要測試單一檔案,去 package.json:

    "scripts": {
      "test": "jest <輸入想要測試的檔案名稱>"
    }
    
  2. 如果 npm 的版本比較新,可以直接用 npx jest <檔案名稱>,代表他會在這個專案裡面,找到有沒有 jest 這個東西,然後去執行










Related Posts

Step By Step 部屬紀錄

Step By Step 部屬紀錄

npm 無法安裝 craco

npm 無法安裝 craco

array 類型的內建函式

array 類型的內建函式


Comments