【发布时间】:2021-12-03 16:09:15
【问题描述】:
我有一个来自组件中调用的钩子的函数。
我的组件:
...
const handleCompleteContent = (contentId: string) => {
postCompleteContent(contentId, playerId).then(data => {
if (data === 201) {
...
来电者:
if (isOpen && contentInfo.type === 0 && !contentInfo.isComplete) {
handleCompleteContent(contentInfo.id);
}
测试:
expect(postCompleteContent).toHaveBeenCalled();
从worldhooks导入的函数
import { postCompleteContent } from '~/hooks/worldhooks';
我嘲笑了钩子:
jest.mock('~/hooks/worldhooks');
试图模拟'201'返回函数:
const mockPostCompleteContent = jest.fn(() => ({ data: 201 }));
(postCompleteContent as jest.Mock).mockReturnValue({
postCompleteContent: mockPostCompleteContent,
});
但是,当我运行测试时:
TypeError: postCompleteContent is not a function
50 |
51 | const handleCompleteContent = (contentId: string) => {
> 52 | postCompleteContent(contentId, playerId).then(data => {
| ^
postCompleteContent函数:
export async function postCompleteContent(contentId: string, playerId: string) {
// eslint-disable-next-line react-hooks/rules-of-hooks
const content = { contentId, playerId };
const response = await api.post('Content/CompletedContent', content);
return response.status;
}
api 是axios.create。
怎么了?或者,我该怎么做?
【问题讨论】:
-
mockPostCompleteContent 和实现之间到底有什么联系?请给minimal reproducible example,而不是断开连接的sn-ps。
-
@jonrsharpe 没有连接!刚刚创建了“mockPostCompleteContent”来尝试将“返回数据:201”设置为 postCompleteContent 模拟函数。我已经用 tmarwen 回答更新了它。
标签: reactjs typescript jestjs enzyme