小编tjo*_*jol的帖子

如何使用 Jest 成功模拟并捕获错误?

几天来我一直在尝试创建一个特定的测试,如果您能深入了解我可能做错了什么,我将不胜感激。

\n\n

我正在尝试模拟数组过滤器函数以引发错误。

\n\n

用户助手.js

\n\n
//filter users by email ending\nconst filterUsersByEmailDomain = (usersArray, emailEnding) => {\n    try {\n        let bizUsers = usersArray.filter(user => {\n            return user.email.endsWith(emailEnding);\n        });\n        return bizUsers;\n    } catch (err) {\n        console.log('error filtering users. Throwing error.');\n        throw err;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

userHelper.test.js:

\n\n
it('should throw', () => {\n        const user1 = {id: 1, email: 'tyler@tyler.com'};\n        const user2 = {id: 2, email: 'tevin@tevin.biz'};\n        const userArray = [user1, user2];\n        const domainEnding = '.biz';\n\n        Array.prototype.filter = jest.fn().mockImplementation(() => {throw new Error()});\n\n …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing node.js jestjs

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

javascript ×1

jestjs ×1

node.js ×1

unit-testing ×1