Jest:it.each中用toMatchInlineSnapshot报错,求解决方案
解决Jest it.each中使用toMatchInlineSnapshot报错的问题
问题原因
Jest的inline快照是基于代码中toMatchInlineSnapshot调用的位置来唯一标识和存储快照内容的。当用it.each批量生成测试用例时,所有用例会共享同一个toMatchInlineSnapshot的调用位置,Jest无法区分不同测试实例的快照,因此抛出错误Jest: Multiple inline snapshots for the same call are not supported。
这种问题在Jest 29.x版本后更容易出现——新版本对inline快照的唯一性检查变得更严格,而你更新的依赖中包含了jest-environment-jsdom@29.4.0,间接引入了这个更严格的检查逻辑。
解决方案
方案1:改用toMatchSnapshot(推荐)
toMatchSnapshot会将所有测试用例的快照内容存储在单独的.snap文件中,每个it.each生成的测试用例都会对应独立的快照条目,不会出现位置冲突。
修改测试代码如下:
import { deleteMe } from './deleteMe'; describe('simplest string matching', () => { it.each([['one'], ['two'], ['three'], ['four'], ['five'], ['six']])( 'matches snapshot for input %s', (inputVal) => { expect(deleteMe(inputVal)).toMatchSnapshot(); }, ); });
执行yarn test -u即可正常更新快照,所有用例的快照会被正确写入对应的.snap文件。
方案2:拆分it.each为独立it测试块(仅适用于少量用例)
如果坚持使用inline快照,只能放弃it.each的批量写法,为每个输入单独编写it测试,确保每个toMatchInlineSnapshot调用都有唯一的代码位置:
import { deleteMe } from './deleteMe'; describe('simplest string matching', () => { it('matches snapshot for input one', () => { expect(deleteMe('one')).toMatchInlineSnapshot(`"this is function returning: one"`); }); it('matches snapshot for input two', () => { expect(deleteMe('two')).toMatchInlineSnapshot(`"this is function returning: two"`); }); it('matches snapshot for input three', () => { expect(deleteMe('three')).toMatchInlineSnapshot(`"this is function returning: three"`); }); // 其余用例依次编写 });
这种方式虽然能解决报错,但会增加代码冗余,仅适合测试用例数量较少的场景。
内容的提问来源于stack exchange,提问作者Akber Iqbal
相关产品推荐
相关产品推荐

