如何使用Jest模拟带命名空间枚举的React Native类组件?
The issue you're hitting is that your original mock treats GoogleSigninButton as a plain object, but React expects it to be a valid component type (a function or class). At the same time, you need to preserve the Size and Color enumerations that are attached to the component class.
Here's how to fix the mock properly:
jest.mock('react-native-google-signin', () => { // Create a minimal mock component - it just needs to be a valid React component const MockGoogleSigninButton = () => null; // Attach the Size and Color enums directly to the mock component, just like the real one MockGoogleSigninButton.Size = { Standard: 0, Wide: 1, Icon: 2 }; MockGoogleSigninButton.Color = { Light: 0, Dark: 1 }; return { GoogleSigninButton: MockGoogleSigninButton }; });
Why this works:
MockGoogleSigninButtonis a simple function component (valid for React rendering) that returnsnull—we don't need actual visual output for testing, just a valid component type.- By attaching
SizeandColoras properties of the mock component, we replicate the structure of the realGoogleSigninButtonclass, which has those enumerations as static members. This lets your test code accessGoogleSigninButton.Size.WideandGoogleSigninButton.Color.Darkwithout errors.
If you want a slightly more realistic mock (e.g., to test props like testID), you can update the component to render a basic element:
const MockGoogleSigninButton = (props) => { return <View testID={props.testID} />; };
This way, you can even query the component in your tests using its testID, just like you would with the real button.
内容的提问来源于stack exchange,提问作者uioporqwerty
相关产品推荐
相关产品推荐

