如何在测试用例中模拟变量和函数



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'}
</>
)
}

`

我想为这个组件编写JEST测试用例。我无法模拟存储和存储中的值,即"lang"、"apiCall"我想将一些默认值设置为"lang",并希望"apiCall"返回特定值。此外,我如何在测试用例文件中将值"setShowChild"设置为"true"作为初始值

我尝试了几种模拟商店的方法,比如:

`

jest.mock('../store_path', () => ({
lang: 'en',
apiCall: jest.fn(() => {return someValue })
}))

`

这里我得到的错误是:TypeError:(0,_store.default)不是函数

我也试过

`

const appStore = jest.mock('../store_path', () => jest.fn())
appStore.mockImplementation(() => ({
lang: 'en',
apiCall: jest.fn(() => {return someValue })

}))`

在这里我得到的错误是:appStore.mockImplementation不是函数

看起来你正在尝试模拟默认导出,在这种情况下,它可以被模拟为低于

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')}))
}))

相关内容

  • 没有找到相关文章

最新更新