【问题标题】:How to fix TS error 'type is missing' when working with jest and History?使用 jest 和 History 时如何修复 TS 错误“缺少类型”?
【发布时间】:2020-05-08 06:41:39
【问题描述】:

我正在编写测试并且我正在使用模拟 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>
);

Typescript 下划线 location: { } 并引发上述错误。我是否错误地扩展了History?我需要一个location 在这里作为一个空对象,我不想使用any 类型。

【问题讨论】:

    标签: javascript reactjs typescript jestjs


    【解决方案1】:

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

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

    【讨论】:

    • 它仍然抛出类似的错误,Type '{ push: Mock&lt;any, any&gt;; createHref: () =&gt; string; location: Location&lt;IHistoryMock&gt;; listen: Mock&lt;any, any&gt;; }' is missing the following properties from type 'History&lt;IHistoryMock&gt;': length, action, replace, go, and 3 more
    • 尝试使用history中的createBrowserHistory函数来创建History mock。这应该是一个更好的解决方案,而不是自己创建 History mock。
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 2011-11-26
    • 2021-11-13
    • 1970-01-01
    • 2021-09-14
    • 2019-08-25
    • 2020-10-31
    • 2020-11-18
    相关资源
    最近更新 更多