You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest问题:模拟API响应后组件数据未成功设置

问题与代码示例

Index.js

import React, {useEffect} from 'react'
import store from '../store_path'
import loadable from '@loadable/component'
import { apiCall } from './apiService_path'
import useTokenHook from 'hook_path'
const ChildComponent = loadable(() => import('../childComponent_path'))

export const ParentComponent = () => {
const token = useTokenHook()
const [data, setData] = useState({})
const [showChild, setShowChild] = useState(false)
const lang = store(state => state.lang)
const apiCall = store(state => state.apicall)

const myFn = async() => {
    const res = await apiCall();
    console.log('[RES DATA]: ', res)
    setData(res)
    setShowChild(true)
}

useEffect(() => { myFn() }, [])

return(
    <>
        {showChild ? <ChildComponent data={data} /> : 'No data found'}
    </>
)
}

Index.test.js

import {mockData} from '../mockdata_path'

jest.mock('./apiService_path', () => {
    apiCall: () => (mockData)
})

test('component to be defined', () => {
    render(<Component />)
})

当前问题

模拟的服务已返回mockData,且控制台能看到该数据,但setData等setter函数的代码未被测试用例覆盖。尝试模拟setter函数也未解决问题,不清楚问题出在哪里。

内容的提问来源于stack exchange,提问作者Urvesh Nagda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:30:45