透過 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' });
});
});
寫了三個 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:
Shadowing Properties in JavaScript