Jest使用匹配器(Matchers)讓你可以運用各種方式測試你的代碼。 這篇文檔將向你介紹一些常用的匹配器, 在expect API可以看到完整的列表。
最簡單的測試值的方法是看是否精確匹配。
test('two plus two is four',()=>{
expect(2+2).toBe(4);
});
在此代碼中,?expect (2 + 2)
? 返回一個?expect
?的對象。 你通常不會對這些?expect
?對象調(diào)用過多的匹配器。 在此代碼中,?.toBe(4)
? 是匹配器。 當(dāng) Jest 運行時,它會跟蹤所有失敗的匹配器,以便它可以為你打印出很好的錯誤消息。
?toBe
? 使用 ?Object.is
?來測試精確相等。 如果想要檢查對象的值,請使用 ?toEqual
?代替:
test('object assignment',()=>{
const data ={one:1};
data['two']=2;
expect(data).toEqual({one:1, two:2});
});
?toEqual
遞歸檢查對象或數(shù)組的每個字段。
你還可以測試相反的匹配︰
test('adding positive numbers is not zero',()=>{
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 讓你明確你想要什么。
toBeNull
? 只匹配 ?null
?toBeUndefined
?只匹配 ?undefined
?toBeDefined
?與 ?toBeUndefined
?相反toBeTruthy
?匹配任何 ?if
? 語句為真toBeFalsy
?匹配任何 ?if
?語句為假例如:
test('null',()=>{
const n =null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero',()=>{
const z =0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
你應(yīng)該用匹配器將你的代碼和你想要的內(nèi)容進行最精確的匹配。
大多數(shù)的比較數(shù)字有等價的匹配器。
test('two plus two',()=>{
const value =2+2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
對于比較浮點數(shù)相等,應(yīng)當(dāng)使用 ?toBeCloseTo
?而不是 ?toEqual
?,因為你不希望測試取決于一個小小的舍入誤差。
test('兩個浮點數(shù)字相加',()=>{
const value =0.1+0.2;
//expect(value).toBe(0.3); 這句會報錯,因為浮點數(shù)有舍入誤差
expect(value).toBeCloseTo(0.3);// 這句可以運行
});
你可以檢查對具有 ?toMatch
?正則表達式的字符串︰
test('there is no I in team',()=>{
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph',()=>{
expect('Christoph').toMatch(/stop/);
});
你也可以通過 ?toContain
?來檢查一個數(shù)組或可迭代對象是否包含某個特定項:
const shoppingList =[
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('the shopping list has beer on it',()=>{
expect(shoppingList).toContain('beer');
expect(newSet(shoppingList)).toContain('beer');
});
如果要測試特定函數(shù)在調(diào)用時是否拋出錯誤,請使用?toThrow
?.
function compileAndroidCode(){
thrownewError('you are using the wrong JDK');
}
test('compiling android goes as expected',()=>{
expect(compileAndroidCode).toThrow();
expect(compileAndroidCode).toThrow(Error);
// You can also use the exact error message or a regexp
expect(compileAndroidCode).toThrow('you are using the wrong JDK');
expect(compileAndroidCode).toThrow(/JDK/);
});
以上這些內(nèi)容只是淺嘗輒止,想要了解更多有關(guān)匹配器的完整列表,請查閱參考文檔。
一旦你學(xué)會了如何使用匹配器后,接下來可以學(xué)習(xí) Jest 是如何測試異步代碼的。
更多建議: