gpt4 book ai didi

reactjs - 如何使用 jest 模拟类和命名空间枚举?

转载 作者:行者123 更新时间:2023-12-04 14:19:27 27 4
gpt4 key购买 nike

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 属性,这样它就不会抛出“无法读取未定义的属性大小”?

最佳答案

我已经通过以下修改修复了它:

在我的测试中:

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)。

关于reactjs - 如何使用 jest 模拟类和命名空间枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56510367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com