gpt4 book ai didi

javascript - 测试函数以在 Jest 中抛出错误

转载 作者:行者123 更新时间:2023-12-01 16:25:21 25 4
gpt4 key购买 nike

我有这样一个功能要测试:

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期望将一个函数传递给expect,而不是其调用的结果。

所以你必须用匿名函数包装你的函数调用:

expect(() => {
checkTextEmpty(elem)
}).toThrow(Error);

关于javascript - 测试函数以在 Jest 中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62680040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com