我有以下上下文
Home.tsx
export const ThemeContext = React.createContext(null)
const Home = () => {
const { width } = Dimensions.get("window")
const [theme, setTheme] = React.useState({
active: 0,
heightOfScrollView: 0,
profileWidth: width * 0.2,
scrolledByTouchingProfile: false
})
const horizontalScrollRef = React.useRef<ScrollView>()
const verticalScrollRef = React.useRef<ScrollView>()
return (
<>
<SafeAreaView style={styles.safeAreaContainer} />
<Header title="Contacts" />
<ThemeContext.Provider value={{ theme, setTheme }}>
在组件A中,我有一个按钮,它在上下文中改变
const onProfileTouched = (index: number) => {
setTheme({ ...theme, active: index });
};
这将导致一个图像处于活动状态
const ImageCircle = ({ active, uri }: Props) => {
return (
<View
style={
active
? { ...styles.parentView, ...styles.active }
: { ...styles.parentView }
}>
<Image source={uri} width={30} height={30} />
</View>
);
};
现在,我想写一个测试用例(我以前没有写过测试用例)来确认状态实际上已经改变,或者可能是一个活动的边框被添加到图像
我给我的按钮添加了一个testd,我用来触发一个事件
it('changes active on profile clicked', () => {
const { getByTestId } = render(<Home />);
fireEvent.press(getByTestId('HScroll3.button'));
});
现在,我不确定如何获取上下文的值或更改样式,以便我可以确认按钮按下的组件确实是活动的
我正在使用import {render, fireEvent} from '@testing-library/react-native'
,但可以改变。
使用测试库,您希望检查可视输出,而不是内部状态。这样你的测试就更有价值了,因为终端用户并不关心你是否使用了上下文、状态或其他东西,他们关心的是按钮是否有"活动"。状态。因此,如果在某些时候您决定改变主意并完全重构主题,您的测试仍然会给您价值和信心。
我建议安装@testing-library/jest-native
,你只需要添加这个setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"]
到您的Jest配置,或者在您的测试设置文件中导入extend-expect
文件。
一旦你设置好了,你就可以开始了。
我不知道你的styles.active
风格是什么,但让我们假设它是例如{ borderColor: '#00ffff' }
。在ImageCircle
组件的View
上添加一个testID
道具,例如testID="imageCircleView"
。然后,为了测试一切是否如您所期望的那样工作,您只需要在测试中添加以下代码:
expect(getByTestId('imageCircleView')).toHaveStyle({ borderColor: '#00ffff' });
就是这样。