首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React和Typescript -由于类型错误“将类型'Global & typeof globalThis‘转换为类型’GLOBALWithFetchMock...‘,测试失败...”

React和Typescript -由于类型错误“将类型'Global & typeof globalThis‘转换为类型’GLOBALWithFetchMock...‘,测试失败...”
EN

Stack Overflow用户
提问于 2021-03-29 23:49:56
回答 1查看 353关注 0票数 0

使用React和Typescript非常棒,但有时会导致令人费解的问题。在本例中,我的所有测试都失败了,并出现了与jest-fetch-mock相关的相同错误:

代码语言:javascript
复制
> 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并重新安装,清除缓存并更改节点版本,但没有任何变化。

EN

回答 1

Stack Overflow用户

发布于 2021-03-29 23:49:56

如果您在setUpTests.ts中将GlobalWithFetchMock声明为全局类型,而Typescript仍然出错,请尝试将全局类型包装在方括号"()“中,并将初始设置为unknown

修改自

代码语言:javascript
复制
const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock

代码语言:javascript
复制
const customGlobal: GlobalWithFetchMock = (global as unknown) as GlobalWithFetchMock

您应该能够成功地再次运行您的测试,并显示许多绿色标记:)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66857360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档