你也可以使用Jest的“匹配器”來測試數(shù)據(jù)荷愕。有很多不同的匹配器邻眷,所以這篇文章只會介紹最常用的幾種蜒茄。
普通匹配
最簡單的的測試方法就是看兩個比較值是否相等:
test('2加2等于',()=>{
? ? expect(2+2).toBe(4);
});
在這段代碼中,expect(2 + 2) 返回一個“expectation”對象十艾。針對expectation對象猜丹,你除了調(diào)用匹配器停巷,其他的你什么也做不了胖眷。在這段代碼中厌杜,.toBe(4)就是匹配器奉呛。當Jest運行時计螺,它會跟蹤所有的匹配器,如果有失敗的匹配就會打印出錯誤消息瞧壮。
把toBe換成===效果是一樣的登馒。如果你想檢查一個對象的值,那么就要用 toEqual 來代替了:
test('對象分配屬性',()=>{
? ? const data={one:1};
? ? data['two']=2;
? ? expect(data).toEqual({one:1,two:2});
});
toEqual 會遞歸的檢查數(shù)咆槽;組或?qū)ο蟮拿恳粋€地方陈轿。
你同樣可以進行反向測試:
test('正數(shù)相加不為零',()=>{
? ? for(let a=1;a<10;a++){
? ? ? ? for(let b=1;b<10;b++){
? ? ? ? ? ? expect(a+b).not.toBe(0);
? ? ? ? }
? ? }
});
很多時候測試需要區(qū)分 undefined,null和false秦忿,但是你有不想做這些麻煩的事麦射。那jest已經(jīng)為你準備好了很多助手方法專門解決這些問題。
-- toBeNull 只匹配 null
-- toBeUndefined 只匹配 undefined
-- toBeDefined 是 toBeUndefined 的反匹配
-- toBeTruthy 匹配 if 語句期望得到 true 的
-- toBeFalsy 匹配 if 語句期望得到 false 的
舉個例子:
test('null',()=>{
? ? const n=null;
? ? expect(n).toBeNull();
? ? expect(n).toBeDefined();
? ? expect(n).not.toBeUndefined();
? ? expect(n).not.toBeTruthy();
? ? expect(n).toBeFalsy();
});
test('0',()=>{
? ? const z=0;
? ? expect(z).not.toBeNull();
? ? expect(z).toBeDefined();
? ? expect(z).not.toBeUndefined();
? ? expect(z).not.toBeTruthy();
? ? expect(z).toBeFalsy();
});
你應該根據(jù)你的代碼來選擇最佳的匹配器灯谣。
數(shù)字的比較都用對應的匹配器潜秋。
test('2加2',()=>{
? ? const value=2+2;
? ? expect(value).toBeGreaterThan(3);//大于匹配器
? ? expect(value).toBeGreaterThanOrEqual(3.5);//大于或等于匹配器
? ? expect(value).toBeLessThan(5);//小于匹配器
? ? expect(value).toBeLessThanOrEqual(4.5);//小于或等于匹配器
? ? // toBe 和 toEqual 對數(shù)字來說效果相等
? ? expect(value).toBe(4);
? ? expect(value).toEqual(4);
});
如果你不希望浮點數(shù)的測試存在誤差,請使用 toBeCloseTo 來代替 toEqual酬屉。
test('浮點數(shù)相加',()=>{
? ? const value=0.1+0.2;
? ? expect(value).not.toBe(0.3);// 錯誤的方法半等,因為存在誤差揍愁。
? ? expect(value).toBeCloseTo(0.3);// 正確的方法呐萨。
});
對于字符串你可以使用 toMatch 配合正則表達式。
test('team 中沒有 i ',()=>{
? ? expect('team').not.toMatch(/I/);
});
test('但是 Christoph 中有 stop',()=>{
? ? expect('Christoph').toMatch(/stop/);
});
測試數(shù)組是否包含特定的元素可以使用 toContain莽囤。
const shoppingList=[
? ? 'diapers',
? ? 'kleenex',
? ? 'trash bags',
? ? 'paper towels',
? ? 'beer',
];
test('shopping 列隊是有 beer 的',()=>{
? ? expect(shoppingList).toContain('beer');
});
如果你想測試某個函數(shù)被調(diào)用的時候是否會拋出錯誤谬擦,請使用 toThrow。
function compileAndroidCode(){
? ? throw new ConfigError('你使用了錯誤的JDK');
}
test('編譯 android',()=>{
? ? expect(compileAndroidCode).toThrow();
? ? expect(compileAndroidCode).toThrow(ConfigError);
? ? // 你還可以匹配完整的錯誤消息或正則表達式
? ? expect(compileAndroidCode).toThrow('你使用了錯誤的JDK');
? ? expect(compileAndroidCode).toThrow(/JDK/);
});