Jest测试中共享全局变量问题:Shopresult未被读取报错排查
问题原因及解决方案
根本原因
你在beforeAll的.then回调函数里,用const Shopresult重新声明了一个局部变量,这个变量和外部describe作用域里的let Shopresult是两个完全独立的变量:
- 外部的
let Shopresult只被声明,从来没有被赋值,所以TypeScript提示它“已声明但未读取”; - 内部的局部
Shopresult只在.then回调的作用域内有效,外部的afterAll根本访问不到它,导致afterAll里的Shopresult.shopId实际是在访问一个未赋值的变量。
修复代码
方案1:移除内部的const,直接赋值给外部变量
describe("test", () => { let Shopresult: Shop; beforeAll(async () => { await getConnection(LocalOrmconfig).then(async () => { // 去掉const,直接给外部的Shopresult赋值 Shopresult = await getRepository(Shop).save(mockData); }); }); afterAll(async () => { await getConnection(LocalOrmconfig).then(async () => { await getRepository(PricingPattern) .createQueryBuilder() .delete() .where({ shopId: Shopresult.shopId }) .execute(); }); }); });
方案2:用async/await替代.then,避免回调嵌套和变量遮蔽(更推荐)
describe("test", () => { let Shopresult: Shop; beforeAll(async () => { // 直接用await替代.then,代码更简洁 await getConnection(LocalOrmconfig); Shopresult = await getRepository(Shop).save(mockData); }); afterAll(async () => { await getConnection(LocalOrmconfig); await getRepository(PricingPattern) .createQueryBuilder() .delete() .where({ shopId: Shopresult.shopId }) .execute(); }); });
额外说明
使用async/await风格的异步代码,不仅能避免回调嵌套导致的变量作用域问题,还能让代码逻辑更清晰,更易维护。
内容的提问来源于stack exchange,提问作者Heisenberg
相关产品推荐
相关产品推荐

