You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest模拟带命名空间枚举的React Native类组件?

Correct Jest Mock for react-native-google-signin's GoogleSigninButton Component

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:

  • MockGoogleSigninButton is a simple function component (valid for React rendering) that returns null—we don't need actual visual output for testing, just a valid component type.
  • By attaching Size and Color as properties of the mock component, we replicate the structure of the real GoogleSigninButton class, which has those enumerations as static members. This lets your test code access GoogleSigninButton.Size.Wide and GoogleSigninButton.Color.Dark without 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:08:07