javascript - 使用 jest 和 History 时如何修复 TS 错误“缺少类型”?
问题描述
我正在编写测试并且我正在使用模拟history
对象,但是 TS 不断抛出以下错误:
Type '{}' is missing the following properties from type 'Location<IHistoryMock>': pathname, search, state, hash
我不知道如何解决这个问题。我尝试过扩展历史界面并以我能想到的各种方式重写它。这是我到目前为止所拥有的:
import { History, Location } from 'history';
interface IHistoryMock extends History {
location: Location | any;
}
const historyMock: History<IHistoryMock> = { push: jest.fn(), createHref: () => '', location: { }, listen: jest.fn() };
mount(
<Router history={historyMock}>
<Component id="id" />
</Router>
);
打字稿下划线location: { }
并引发上述错误。我是否错误地扩展History
?我需要 alocation
在这里成为一个空对象,并且我不想使用该any
类型。
解决方案
您可以使用库中的createLocation
函数history
来创建位置模拟
import { createLocation } from 'history';
...
const historyMock: History<IHistoryMock> = { push: jest.fn(), createHref: () => '', location: createLocation('/'), listen: jest.fn() };
推荐阅读
- reactjs - 在“未知”类型上找不到具有“字符串”类型参数的索引签名
- python - Python文字冒险店
- javascript - 如何将现有值输入到 React 中的输入字段中以进行编辑表单
- spring-boot - Eureka 和 Feign 客户端防止 springboot 关闭
- javascript - HTML/CSS - 轮播幻灯片中的多个图像
- javascript - 从承诺将数据推送到局部变量?
- javascript - Vanilla Javascript 中是否有 requireJS toUrl 等价物
- truffle - Truffle 部署资金不足(尽管使用了 Truffle 的总价格估算)
- html - 是否可以在网页内制作网页视图?
- python - 熊猫 - 创建新列 - 如果另一个列值在列表中(正确的方式)