iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

透過 Lodash 這套 JavaScript library,觀察測試怎麼寫

簡介

Lodash JavaScript library,提供非常多常用的函式,包含陣列、字串、物件、數值...等的處理

資料夾結構

# Lodash
lodash
├── .commitlintrc.js
├── .editorconfig
├── .eslintignore
├── .eslintrc
├── .git
├── .gitattributes
├── .github
├── .gitignore
├── .husky
├── .prettierignore
├── .prettierrc
├── CHANGELOG
├── LICENSE
├── README.md
├── SECURITY.md
├── bunfig.toml
├── package.json
├── src
├── test
├── tsconfig.json
└── yarn.lock

test 資料夾放在根目錄底下

吸收額外關鍵字

從根目錄的設定檔觀察專案用到的工具/技術:

  • Bun
  • Husky
  • Prettier
  • ESLint
  • Commitlint
  • TypeScript

測試檔案

以 invert(object) function 為例,使用 invert 會建立一個物件,並將傳入 object 的 key 和 value 做反轉,如果 key 相同,會覆蓋 value 值,例如:

var object = { 'a': 1, 'b': 2, 'c': 1 };

_.invert(object);
// => { '1': 'c', '2': 'b' }

lodash/test/invert.spec.js 測試檔怎麼寫:

import invert from '../src/invert';

describe('invert', () => {
    it('should invert an object', () => {
        const object = { a: 1, b: 2 };
        const actual = invert(object);

        expect(actual).toEqual({ 1: 'a', 2: 'b' });
        expect(invert(actual)).toEqual({ a: '1', b: '2' });
    });

    it('should work with values that shadow keys on `Object.prototype`', () => {
        const object = { a: 'hasOwnProperty', b: 'constructor' };
        expect(invert(object)).toEqual({ hasOwnProperty: 'a', constructor: 'b' });
    });

    it('should work with an object that has a `length` property', () => {
        const object = { 0: 'a', 1: 'b', length: 2 };
        expect(invert(object)).toEqual({ a: '0', b: '1', 2: 'length' });
    });
});
  • describe 區塊:放置相關的 test 區塊放在一起,方便分類測試案例
  • it 區塊:測試案例 Test Case,也可以寫做 test,兩者都可以

寫了三個 Test Case,

  • should invert an object
  • should work with values that shadow keys on Object.prototype
  • should work with an object that has a length property

一個是一般的物件,剩下兩個分別檢查 shadow keys 為內建 method 或是 key 名稱為 length 這些特殊字的情境。


補充

單元測試 Guidelines,參考自 How to write your first unit test in JavaScript:

  1. 盡可能讓每個測試簡短、簡單
  2. 考慮正反向的情境
  3. 拆解過長或是太複雜的函式,太多邏輯很難寫測試
  4. 跑測試要快,盡量避免需要網路或是資料庫的連線,或是直接使用 mock 模擬網路和資料庫的連線

參考資源

Shadowing Properties in JavaScript


上一篇
[測試] Visual Testing
下一篇
[Conf] DevOps 到 DevSecOps
系列文
那些經過腦海一瞬的關鍵字們 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言