本篇文章主要介紹 Jest 測試框架,並應用在 ES6 語法進行 import,且不使用 Babel 編譯

  • 建立主程式
  • 建立測試
  • 自動重新執行測試

建立主程式

  1. 建立一個專案 「Project」,在路徑 D:/Workspace/JS 建立一個資料夾 Project,建立後路徑如下

    1
    2
    JS
    └─ Project
  2. 建立 sum.js 填入以下內容

    1
    2
    3
    export function sum(a, b) {
    return a + b
    }
  3. 建立 main.js 填入以下內容

    1
    2
    3
    import { sum } from './sum.js'

    console.log(sum(5, 7))
  4. 建立 package.json 填入以下內容

    1
    2
    3
    {
    "type": "module"
    }
  5. 執行 main 確認可正常運行

    1
    2
    # From within D:/Workspace/JS/Project
    node ./main.js
  6. 最後路徑如下

    1
    2
    3
    4
    5
    JS
    └─ Project
    ├─ package.json
    ├─ main.js
    └─ sum.js

建立測試

  1. 建立 sum.test.js 填入以下內容

    1
    2
    3
    4
    5
    import { sum } from './sum'

    test('Check the result of 5 + 2', () => {
    expect(sum(5, 2)).toBe(7)
    })
  2. 安裝 Jest 測試框架

    1
    2
    # From within D:/Workspace/JS/Project
    npm install jest --save-dev
  3. 安裝後路徑如下

    1
    2
    3
    4
    5
    6
    7
    8
    JS
    └─ Project
    ├─ node_modules
    | └─ ...
    ├─ package.json
    ├─ package-lock.json
    ├─ main.js
    └─ sum.js
  4. 修改 package.json,加入以下內容,意思是 npm test 會執行 jest

    1
    2
    3
    "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
    },
  5. 修改 package.json,加入以下內容,意思是將 jest 的屬性 transform 設定為空

    1
    2
    3
    "jest": {
    "transform": {}
    }
  6. 最後整體完成的 package.json 如下,版本號可能不一樣

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    {
    "type": "module",
    "devDependencies": {
    "jest": "^29.1.1"
    },
    "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
    },
    "jest": {
    "transform": {}
    }
    }
  7. 最後執行測試

    1
    2
    # From within D:/Workspace/JS/Project
    npm test

自動重新執行測試

當開啟自動重新執行測試時,當檔案發生變化,或是與 git 版本發生變化時,就會重複執行測試,可以不用改完程式碼後手動執行測試

  • 修改 package.json 的 scripts,改成 watch 模式需要包含 git 版控

    1
    2
    3
    "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch"
    }
  • 改成全部模式不需要版控

    1
    2
    3
    "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"
    }