【发布时间】: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