首页 > 解决方案 > 使用 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类型。

标签: javascriptreactjstypescriptjestjs

解决方案


您可以使用库中的createLocation函数history来创建位置模拟

import { createLocation } from 'history';
...
const historyMock: History<IHistoryMock> = { push: jest.fn(), createHref: () => '', location: createLocation('/'), listen: jest.fn() };

推荐阅读