使用Jest测试类时遇到意外行为及TypeError报错求助
问题分析与解决方案
报错原因
这和Jest的异步行为无关,核心问题是对象解构的时机错误:
- 当你执行
const { a, computedValue, computedInstances, initialize } = new Store();时,computedValue作为类的getter属性会立即执行,返回当时的[this.a]——此时this.a还未初始化,值为undefined。 - 后续调用
initialize()确实会给Store实例的a赋值,但之前解构出来的computedValue变量已经是[undefined],不会自动同步实例的更新。 - 测试中
expect(computedValue[0].b)自然会抛出Cannot read properties of undefined错误,因为computedValue[0]是undefined。
解决方案
方案1:保留Store实例引用,按需访问getter
不要解构getter属性,每次通过实例访问,确保获取的是最新计算的值:
test('test', () => { const store = new Store(); store.initialize(); expect(store.computedValue[0].b).toBe('B'); store.computedValue[0].changeValue(); expect(store.a.b).toBe('changed B'); expect(store.computedInstances.v[0].b).toBe('changed B'); });
方案2:延迟解构getter属性
如果一定要使用解构,需在initialize()执行完成后,再解构需要的属性:
test('test', () => { const store = new Store(); store.initialize(); // 初始化完成后再解构,确保获取的是更新后的值 const { a, computedValue, computedInstances } = store; expect(computedValue[0].b).toBe('B'); computedValue[0].changeValue(); expect(a.b).toBe('changed B'); expect(computedInstances.v[0].b).toBe('changed B'); });
补充说明
类的getter属性只有在通过实例访问时才会重新计算返回值,解构操作是一次性获取当前时刻的值,不会与实例的后续状态变化绑定。你之前遇到的“测试被函数修改后的类变量时的类似问题”,本质也是同样的逻辑错误——提前解构获取了未更新的值。
内容的提问来源于stack exchange,提问作者mymoto
相关产品推荐
相关产品推荐

