如何解决React 和 Typescript - 由于类型错误“将类型'Global & typeof globalThis' 转换为类型'GlobalWithFetchMock'...”,测试失败
使用 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 并重新安装,清除缓存并更改节点版本,但没有任何改变。
解决方法
如果您在 GlobalWithFetchMock
中将 setUpTests.ts
声明为全局类型并且 Typescript 仍然在抱怨,请尝试将全局类型包装在方括号“()”中并初始设置为 unknown
修改自
const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock
到
const customGlobal: GlobalWithFetchMock = (global as unknown) as GlobalWithFetchMock
您应该能够再次成功运行测试并显示大量绿色:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。