ParentComponent.js
import React, {useEffect} from 'react'
import store from '../store_path'
import loadable from '@loadable/component'
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();
setData(res)
setShowChild(true)
}
useEffect(() => {
myFn()
}, [])
return (
<>
{showChild
? <ChildComponent data={data} />
: 'No data found'
}
</>
)
}
I want to write Jest test cases for this component.
I am not able to mock store and values from store i.e. lang
, apiCall
. I want to set some default value to lang
and I want to apiCall
to return specific value. Also how can I set value setShowChild
to true
as initial value in test case file?
I tried few approaches to mock store like:
jest.mock('../store_path', () => ({
lang: 'en',
apiCall: jest.fn(() => {
return someValue
})
}))
Here I am getting error as:
TypeError: (0, _store.default) is not a function
I also tried:
const appStore = jest.mock('../store_path', () => jest.fn())
appStore.mockImplementation(() => ({
lang: 'en',
apiCall: jest.fn(() => {
return someValue
})
}))
And here I am getting error as:
appStore.mockImplementation is not a function
It looks like you are trying to mock default export in which case it can be mocked something like below
jest.mock('../store_path', () => ({
default: jest.fn()
// value for first store() call
.mockReturnValueOnce('en')
// value for second store() call since it's async function
.mockReturnValueOnce(() => new Promise((resolve) => { resolve('apiReturnVal')}))
}))