隨着js 越來越強大,日常使用中關於js 的問題也就越突出了,我們需要關注的點也就不能只像以前那樣
只編寫簡單的功能實現,我們同時也需要關注js 的健壯性,測試就是其中一個比較重要的環節,以下
是ava 測試框架的一個簡單使用,關於ava 的介紹可以查看官方文檔
demo 同時集成了簡單的github repo 測試
環境准備
為了測試,代碼使用了typescript,通過tsc 實時編譯
- 項目結構
├── libs
│ ├── app.d.ts
│ └── app.js
├── package.json
├── src
│ └── app.ts
├── tests
│ └── app.js
├── tsconfig.json
- 代碼說明
src 為typescript 的簡單代碼,libs typescript 實時編譯生成的js 文件,tests 目錄為集成的測試,tsconfig.json是關於typescript 的配置
pacakge.json 主要定義依賴以及npm scripts,還有就是github repo push 的配置
{
"name": "@rongfengliang/ava-test-learning",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"ava": "^2.4.0",
"typescript": "^3.6.4",
"zen-observable": "^0.8.14"
},
"scripts": {
"test:live": "ava -v -w",
"test": "ava",
"build:live": "tsc --watch"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
}
}
src/app.ts 待測試的代碼
// define user entity
let user = {
/** user name */
name:"dalong",
/** user age */
age:33
}
// for export default
export default {
user
}
export {
user
}
tests/app.js
import test from 'ava';
import Observable from "zen-observable"
import {user} from "../libs/app"
test('foo', t => {
t.plan(3)
let name = "dalong"
t.log(`input name ${name}`)
return Observable.of(1, 2, 3, 4, 5, 6)
.filter(n => {
return n % 2 === 0;
})
.map(() => t.pass());
});
test.todo('will think about writing this later');
test('bar', async t => {
const bar = Promise.resolve('bar');
t.is(await bar, 'bar');
});
test('username', t => {
t.log("test for username is equal",test.meta.file)
t.is(user.name,"dalong")
});
運行&&測試
- 運行實時ts 編譯
yarn build:live
- 運行實時測試
yarn test:live
- 效果
github repo 發布
- login
npm login --registry=https://npm.pkg.github.com
注意輸入的信息,用戶密碼使用生成的個人token,同時注意token 需要包含操作package 的權限,同時注意項目中pacakge.json
中的名字,當前github 支持的repo 是scope 類型的
- 發布
npm publish
- 效果
說明
以上是一個簡單的測試,實際上ava 功能很強大,同時官方提供的文檔也比較詳細,我們可以結合nyc 提供覆蓋率的處理
參考資料
https://github.com/rongfengliang/ava-test-learning
https://github.com/avajs/ava