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
相关产品推荐
相关产品推荐

