为 useHistory 钩子模拟 react-router-dom 会导致以下错误 - TS2698:Spread types may only be created from object types [英] Mocking react-router-dom for useHistory hook causes the following error - TS2698: Spread types may only be created from object types

查看:71
本文介绍了为 useHistory 钩子模拟 react-router-dom 会导致以下错误 - TS2698:Spread types may only be created from object types的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的一个测试用例中模拟 react-router-dom,以便 useHistory 钩子在我的测试中起作用.我决定使用 jest.mock 来模拟整个模块,并使用 jest.requireActual 来保留我可能不想模拟的其他属性.

I am trying to mock react-router-dom in one of my test cases so that the useHistory hook will function in my tests. I decide to use jest.mock to mock the entire module, and jest.requireActual to preserve the other properties that I may not want to mock.

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    location: {
      pathname: '/list',
    },
  }),
}));

这实际上源自以下问题的高评价解决方案之一:如何在玩笑中模拟 useHistory 钩子?

This is actually derived from one of the highly rated solutions to the following question: How to mock useHistory hook in jest?

但是,TypeScript 编译器在以下行中标记以下错误 ...jest.requireActual('react-router-dom'),

However, the TypeScript compiler is flagging the following error on the following line ...jest.requireActual('react-router-dom'),

TS2698:传播类型只能从对象类型创建.

TS2698: Spread types may only be created from object types.

有趣的是,我只在将 jest 和 ts-jest 更新到最新版本(jest v26)后才会遇到这个问题.当我使用 jest 24.x.x. 时,我没有遇到任何这些问题.

Interestingly, I only face this issue after updating jest and ts-jest to the latest versions (jest v26). I do not face any of these issues when I was using jest 24.x.x.

"@types/jest": "^26.0.4",
"jest": "^26.1.0",
"ts-jest": "^26.1.1",

有谁知道最新的 jest 版本如何解决这个问题?

Does anyone know how to solve this issue for the latest jest versions?

推荐答案

jest.requireActual 返回无法传播的 unknown 类型.

jest.requireActual returns unknown type that cannot be spread.

正确的类型是:

import * as ReactRouterDom from 'react-router-dom';

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom') as typeof ReactRouterDom,
  useHistory: ...,
}));

快速修复是any:

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom') as any,
  useHistory: ...,
}));

这是可以接受的,因为在这种情况下它不会损害类型安全.

It's acceptable because it doesn't impair type safety in this case.

由于 react-router-dom 是 ES 模块,更正确的模拟方式是:

Since react-router-dom is ES module, a more correct way to mock it is:

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom') as any,
  __esModule: true,
  useHistory: ...,
}));

这篇关于为 useHistory 钩子模拟 react-router-dom 会导致以下错误 - TS2698:Spread types may only be created from object types的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆