【问题标题】:How to mock a class and namespace enums using jest?如何使用 jest 模拟类和命名空间枚举?
【发布时间】:2019-10-23 21:48:00
【问题描述】:

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”?

【问题讨论】:

标签: reactjs react-native jestjs


【解决方案1】:

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

在我的测试中:

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 使用来自 NativeModulesRNGoogleSignin 并调用上面重新定义的属性(例如 SIGN_IN_CANCELLED)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2014-07-24
    • 2016-03-27
    • 2023-03-30
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多