Enzyme单元测试中Typescript报错LocationDescriptor类型不存在pathname属性
错误成因
Property 'pathname' does not exist on type 'LocationDescriptor | ((location: Location) => LocationDescriptor)'.
Property 'pathname' does not exist on type 'string'.
以上报错的核心原因是react-router-dom对Link组件to属性的类型定义为联合类型:允许传入字符串、Location对象、或者接收当前Location返回目标Location的函数。TS无法默认你拿到的to属性是包含pathname字段的对象类型,因此直接访问pathname时就会触发类型校验报错,和Enzyme的ShallowWrapper没有关联。
解决方案
三种常见方案按需选择:
- 类型断言(最快解决,适合测试场景)
直接明确告知TS你确定当前to属性是包含pathname的对象类型即可:
// 可以直接断言为包含pathname的对象 expect((links.at(0).prop('to') as { pathname: string }).pathname).toEqual( '/order/DIGITAL/1111' ); // 更规范的写法可以导入react-router内置的Location类型 import type { Location } from 'react-router-dom'; expect((links.at(0).prop('to') as Location).pathname).toEqual( '/order/DIGITAL/1111' );
- 类型收窄(最安全,适合生产/通用代码场景)
先通过类型判断排除to为字符串、函数的情况,TS会自动收窄类型,不需要额外断言:
const to = links.at(0).prop('to'); // 排除函数、字符串类型,确认是包含pathname的对象 if (typeof to === 'object' && 'pathname' in to) { expect(to.pathname).toEqual('/order/DIGITAL/1111'); }
- 直接转为字符串对比(仅适合仅校验路径的场景)
to属性的所有合法取值都可以通过String()转为对应的路径字符串,如果不需要校验state等额外字段,可以直接这么写:
expect(String(links.at(0).prop('to'))).toEqual('/order/DIGITAL/1111');
内容的提问来源于stack exchange,提问作者SeyAde
相关产品推荐
相关产品推荐

