想知道是否有人对如何破解这个问题有一些好的建议.得到了这个测试助手utils,我添加了一些类型:
imp或t { jest } from '@jest/globals'
imp或t React from 'react'
// https://learn.reactnativeschool.com/courses/781007/lectures/14173979
exp或t function mockComponent(moduleName: string, propOverrideFn = (props: Rec或d<string, any>) => ({})) {
const RealComponent = jest.requireActual(moduleName) as React.ComponentType<any>
const CustomizedComponent = (props: Rec或d<string, any>) => {
return React.createElement(
'CustomizedComponent',
{
...props,
...propOverrideFn(props),
},
props.children
)
}
CustomizedComponent.propTypes = RealComponent.propTypes
return CustomizedComponent
}
所以现在我可以这样称呼它
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return mockComponent('react-native/Libraries/Components/Touchable/TouchableOpacity', (props) => {
return {
onPress: props.disabled ? () => {} : props.onPress
}
})
})
但我希望能称之为
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return <MockComponent
module='TouchableOpacity'
onPress={props => props.disabled ? () => {} : props.onPress}
/>
})
或
jest.mock('react-native/Libraries/Components/Touchable/TouchableOpacity', () => {
return <MockComponent
module='TouchableOpacity'
propOverride={props => ({onPress: props.disabled ? () => {} : props.onPress, ...props})}
/>
})