[英]Testing Function to Throw an Error in Jest
我有這樣一個 function 來測試:
export const checkTextEmpty = stringArg => {
if (typeof stringArg !== 'string') {
throw new Error('Provide a string argument to checkTextEmpty function')
}
return stringArg.length === 0 || stringArg.trim() === ''
}
我想測試它是否正確拋出錯誤:
it(
'should throw an error if passed argument is not a string',
() => {
const notStrings = [null, 4, [], {}, undefined, -5]
notStrings.forEach(elem => {
expect(checkTextEmpty(elem)).toThrow(Error)
})
}
)
這是我終端的結果:
utils.js › checkTextEmpty util › should throw an error if passed argument is not a string
Provide a string argument to checkTextEmpty function
117 | export const checkTextEmpty = stringArg => {
118 | if (typeof stringArg !== 'string') {
> 119 | throw new Error('Provide a string argument to checkTextEmpty function')
| ^
120 | }
121 |
122 | return stringArg.length === 0 || stringArg.trim() === ''
at checkTextEmpty (src/scripts/utils/utils.js:119:11)
at forEach (src/scripts/utils/utils.test.js:11:18)
at Array.forEach (<anonymous>)
at Object.it (src/scripts/utils/utils.test.js:10:20)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 0 total
Time: 3.918 s
如何修復我的測試以使其正常工作?
toThrow
期望將function傳遞給expect
,而不是其調用的結果。
所以你必須用匿名 function 來包裝你的 function 調用:
expect(() => {
checkTextEmpty(elem)
}).toThrow(Error);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.