[Jest] Write data driven tests in Jest with test.each
Often, we end up creating multiple unit tests for the same unit of code to make sure it behaves as expected with varied input. This is a good practice, but it can be a little tedious to create what is essentially the same test multiple times. We copy a test, paste it and update the variables that matter. Maybe we do that several times. Then, if we need to update our tests, we update each copy of the test. The good news is, starting with version 23
of Jest, there is built-in support for creating data-driven tests. In this lesson we'll take a handful of unit tests and reduce them down to a single, data-driven test with the new test.each
method in Jest. We'll also look at the alternate version of test.each
that lets us use a tagged template literal to describe the data for our test.
Additional info:
In the Jest docs: https://facebook.github.io/jest/docs/en/api.html#testeachtable-name-fn
Jest cheatsheet: https://github.com/sapegin/jest-cheat-sheet#data-driven-tests-jest-23
describe('isPalindrome - each', () => { const data = [ ['Racecar', true], ['Typewriter', false], ['rotor', true], ['kayak', true], ['Step on no pets', true] ]; test.each(data)('isPalindrome(%s) --- %s', (input, expected) => { const result = isPalindrome(input); expect(result).toBe(expected) }) }) describe('isPalindrome - each template literal', () => { test.each` input | expected ${'Racecar'} | ${true} ${'Typewriter'} | ${false} ${'rotor'} | ${true} `('isPalindrome("$input") - $expected', ({ input, expected }) => { const result = isPalindrome(input) expect(result).toBe(expected) }) })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具