您好,我是这个库react-testing-library
的新手,我非常执着,没有找到任何解决问题的方法。
我尝试测试的是isLoading的状态。当输入useEffect()
时,它将在获取功能结束时将值从true
更改为false
。
代码
const Trends = ({ fetch3MonthlyKpiData, objectId }) => {
const [isLoading, setIsLoading] = useState(true)
const startLoading = () => setIsLoading(true)
const stopLoading = () => setIsLoading(false)
useEffect(() => {
if (objectId && objectId !== '-1') {
startLoading()
fetch3MonthlyKpiData(objectId)
.then(stopLoading)
.catch(stopLoading)
}
}, [objectId])
//more code
}
试验
test('aaaa', () => {
render(<Trends {...mockPropsForComponent} />)
expect(mockPropsForComponent.fetch3MonthlyKpiData).toHaveBeenCalled()
})
我尝试测试isLoading的值,但始终会出现错误。
TypeError:无法读取未定义的属性'then'
有任何建议吗?
当该效果运行道具fetch3MonthlyKpiData尚未传递给组件,并且您没有对其进行验证时,请尝试以下操作:
const Trends = ({ fetch3MonthlyKpiData, objectId }) => {
const [isLoading, setIsLoading] = useState(true)
const startLoading = () => setIsLoading(true)
const stopLoading = () => setIsLoading(false)
useEffect(() => {
if (objectId && objectId !== '-1') {
startLoading()
fetch3MonthlyKpiData(objectId)
.then(stopLoading)
.catch(stopLoading)
}
}, [objectId, fetch3MonthlyKpiData]) //effect runs when both props update their values
//more code
}