【问题标题】:How to mock async method in an interface with Jest?如何在 Jest 的接口中模拟异步方法?
【发布时间】:2021-05-28 18:21:09
【问题描述】:

我在 TypeScript 中有如下界面:

interface Something {
  getValueAsync: () => Promise<number>
}

我正在尝试使用 Jest 创建一个模拟实例。我试过了:

const mock : Something = {
  getValueAsync: jest.fn().mockResolvedValue(123),
};

const mock : Something = {
  getValueAsync: jest.fn(() => Promise.resolve(123)),
};

但是当我运行测试时我的代码总是失败:

TypeError: Cannot read property 'then' of undefined

   7 |
   8 |   useEffect(() => {
>  9 |     if (something) something.getValueAsync().then(setValue);
     |                    ^
  10 |   }, [something]);

如果我使用以下方式创建模拟,则不会发生错误:

const mock : Something = {
  getValueAsync: () => Promise.resolve(123),
};

注意:这发生在 create-react-app 中。失败的代码位于功能组件中,something 的值通过上下文检索。模拟实例通过上下文提供程序传递。

更新:可以在此 repo 上观察到该问题:https://github.com/gfox1984/jest-async 在本地运行时(但在使用 the same repo on codesandbox¯\(ツ)/¯ 时不会)

有什么想法吗?

【问题讨论】:

  • mock.getAsyncValue().then((value) => /* 做某事 */); ???在你的 sn-p 中没有定义一些东西。
  • 是的,我明白了,getAsyncValue 返回 undefined 而不是预期的 Promise,这是我的问题...问题是为什么?
  • 我提交了一个issue on the create-react-app repo,因为我怀疑这个错误与它有关。

标签: reactjs typescript jestjs create-react-app


【解决方案1】:
const mock : Something = {
  getValueAsync: jest.fn(() => Promise.resolve(123)),
};

没问题。尽管对于预期值,您应该使用模拟函数的 mock 属性:

something.getAsyncValue()

expect(something.getAsyncValue.mock.results[0].value).resolves.toBe(123)

stackblitz playground

【讨论】:

  • 不幸的是,这段代码给了我错误。请注意,我不直接使用 something 是我的测试,但我正在测试的组件会(并且失败)
  • 添加了带有工作示例的 stackblitz 链接。在终端控制台中使用jestyarn jest 运行
  • 我将尝试创建一个包含失败场景的沙箱并更新问题。
  • 而且我很伤心......我的场景在 codesandbox I created ? 中有效。也许这与 create-react-app 有关,或者我错过了一些完全不相关的东西......
  • 我确认,放入 create-react-app 中的相同代码失败¯\_(ツ)_/¯ 我将更新问题
猜你喜欢
  • 2019-07-31
  • 2019-01-23
  • 2014-01-27
  • 1970-01-01
  • 2019-01-24
  • 2021-08-11
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
相关资源
最近更新 更多