如何使用玩笑来模拟类和名称空间枚举?

时间:2019-06-08 21:51:41

标签: reactjs react-native jestjs

react-native-google-signin定义以下内容:

export interface GoogleSigninButtonProps extends ViewProps {
  style?: StyleProp<ViewStyle>;
  size?: GoogleSigninButton.Size;
  color?: GoogleSigninButton.Color;
  disabled?: boolean;
  onPress?(): void;
}

export class GoogleSigninButton extends React.Component<GoogleSigninButtonProps> {
  constructor(props: GoogleSigninButtonProps);
}

export namespace GoogleSigninButton {
  enum Size {
    Standard,
    Wide,
    Icon,
  }

  enum Color {
    Light,
    Dark,
  }
}

在我的代码中,我是这样使用的:

<GoogleSigninButton
        style={{ width: 192, height: 48 }}
        size={GoogleSigninButton.Size.Wide}
        color={GoogleSigninButton.Color.Dark}
        onPress={this.authenticate}
        testID={'GoogleAuthenticationButton'}
      />

我已编写测试以尝试进行如下模拟:

jest.mock('react-native-google-signin', () => ({
  GoogleSigninButton: {
    Size: {
      Standard: 0,
      Wide: 1,
      Icon: 2
    },
    Color: {
      Light: 0,
      Dark: 1
    }
  }
}))

但是我遇到以下错误:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

我尝试设置GoogleSigninButton: 'GoogleSigninButton',这将修复预期的返回类型,但会产生其他错误,例如大小和颜色未定义。如果我保持原样,则会收到上面的错误。

我该如何模拟上面的类,以便它返回GoogleSignInButton的字符串,而且还定义了Size和Color属性,从而不会抛出“无法读取未定义的Size属性”?

1 个答案:

答案 0 :(得分:0)

我通过以下修改对其进行了修复:

在我的测试中:

jest.doMock('react-native-google-signin', () => () => {
  const GoogleSigninButton = () => {}
  GoogleSigninButton.Color = {
    Auto: 0,
    Light: 1,
    Dark: 2
  }
  GoogleSigninButton.Size = {
    Icon: 0,
    Standard: 1,
    Wide: 2
  }

  return GoogleSigninButton
})

我还创建了一个包含以下内容的react-native-modules.ts文件:

import { NativeModules } from 'react-native'

NativeModules.RNGoogleSignin = {
  SIGN_IN_CANCELLED: '0',
  IN_PROGRESS: '1',
  PLAY_SERVICES_NOT_AVAILABLE: '2',
  SIGN_IN_REQUIRED: '3'
}

export { NativeModules }

在jest.config.js中,我添加了以下属性:

setupFiles: ['./tests/__mocks__/react-native-modules.ts'],

这是必需的,因为GoogleSignIn使用RNGoogleSignin中的NativeModules并调用上面重新定义的属性(例如SIGN_IN_CANCELLED)。