【问题标题】:React and Typescript - Tests are failing due to type error "Conversion of type 'Global & typeof globalThis' to type 'GlobalWithFetchMock'..."React 和 Typescript - 由于类型错误“将类型 'Global & typeof globalThis' 转换为类型 'GlobalWithFetchMock'...”而导致测试失败
【发布时间】:2021-06-25 16:02:24
【问题描述】:

使用 React 和 Typescript 非常棒,但有时会导致令人头疼的问题。在这种情况下,我的所有测试都因与 jest-fetch-mock 相关的相同错误而失败:

> NODE_ENV=test jest
 FAIL  src/store/index.test.tsx
  ● Test suite failed to run
    src/setupTests.ts:6:43 - error TS2352: Conversion of type 'Global & typeof globalThis' to type 'GlobalWithFetchMock' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
      Property 'fetchMock' is missing in type 'Global & typeof globalThis' but required in type 'GlobalWithFetchMock'.
    6 const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock
                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      node_modules/jest-fetch-mock/types/index.d.ts:15:5
        15     fetchMock: FetchMock;
               ~~~~~~~~~
        'fetchMock' is declared here.

setupTests.ts 文件没有变化,所以可能是由于某些依赖项的更新引起的。 我尝试删除 node_modules 并重新安装,清除缓存并更改节点版本,但没有任何改变。

【问题讨论】:

    标签: javascript reactjs typescript unit-testing jest-fetch-mock


    【解决方案1】:

    如果您在 setUpTests.ts 中将 GlobalWithFetchMock 声明为全局类型,并且 Typescript 仍在抱怨,请尝试将全局类型括在括号“()”中并最初设置为 unknown

    修改自

    const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock
    

    const customGlobal: GlobalWithFetchMock = (global as unknown) as GlobalWithFetchMock
    

    您应该能够再次成功运行测试,并带有大量绿色:)

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2022-01-04
      • 1970-01-01
      • 2020-12-23
      • 2021-11-24
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多