一般我們寫完代碼會這樣測試
function sum (a, b) {
return a + b
}
// 通過console輸出值跟預期的結果對比
console.log(sum(1, 2), 3)
上線的時候會把console都刪掉,但是別人使用的時候又會測一下這個功能是否正常
使用Jest測試,可以避免這樣的問題出現
開始使用
安裝jest和@types/jest包含的聲明文件,聲明文件是定義了一些類型,寫代碼的時候會有提示,如果你熟悉TS,大概明白這個文件了。
npm i jest @types/jest
在package裏面添加一個script腳本
{
"name": "20191019",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/jest": "^24.0.19",
"jest": "^24.9.0"
}
}
默認會測試spec和test結尾的js文件
Jest默認只能測試模塊,我現在把我index.js文件寫的方法導出
export function sum (a, b) {
return a + b
}
qs.sepc.js中測試用例的寫法
// 測試用例的寫法
import { sum } from '../index'
it('測試sum函數', () => {
expect(sum(1, 2)).toBe(3)
})
然後運行代碼npm run test,生成測試報告
分組describe
// 測試用例的寫法
import { sum } from '../index'
// describe表示分組,分組裏面一個個的用例
describe('測試基本方法', () => {
it('測試sum函數', () => {
expect(sum(1, 2)).toBe(3)
})
})
匹配器
相當,不相等,包含,等等,匹配的關係
// describe表示分組,分組裏面一個個的用例
describe('測試基本方法', () => {
it('測試sum函數', () => {
expect(sum(1, 2)).toBe(3)
})
it('測試1+1=2', () => {
expect(1 + 1).toBe(2)
})
it ('對象比較', () => {
expect({name: 1}).toEqual({name: 1})
})
})
it('測試不相等', () => {
expect(1+1).not.toBe(3) // 1+1不等3
expect(3).toBeLessThan(5) // 3<5
})
it('測試包含', () => {
expect('hello').toContain('h')
expect('hello').toMatch(/h/)
})
測試DOM
it('測試刪除DOM', () => {
document.body.innerHTML = `<div><button></button></div>`
let button = document.querySelector('button')
expect(button).not.toBe(null)
// 自己寫的移除的DOM方法
removeNode(button);
button = document.querySelector('button')
expect(button).toBe(null)
})
測試異步
// 回調
export const getDataCallback = fn => {
setTimeout(() => {
fn({name: 'callback'})
}, 1000);
}
// promise
export const getDataPromise = fn => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({name: 'callback'})
}, 1000);
})
}
import { getDataCallback, getDataPromise } from '../index'
// 異步回調
it('測試回調函數', (done) => {
getDataCallback((data) => {
expect(data).toEqual({ name: 'callback' })
done() // 標識調用完成
})
})
it('測試promise', () => {
// 返回的promise會等待完成
return getDataPromise().then(data => {
expect(data).toEqual({ name: 'callback' })
})
})
it('測試promise', async () => {
// 使用await語法
const data = await getDataPromise()
expect(data).toEqual({ name: 'callback' })
})