如何将样式化组件主题与react本机测试库结合使用



我有一个简单的组件:

import React, { FunctionComponent } from 'react';
import { ViewStyle, StyleProp, StyleSheet } from 'react-native';
import {
RoundedCardBackground,
} from './index';
type RoundedCardProps = {
style?: StyleProp<ViewStyle>;
shadow?: boolean;
};
const RoundedCard: FunctionComponent<RoundedCardProps> = ({
style,
children,
shadow,
}) => {
let shadowStyle = shadow ? styles.shadow : undefined;
return (
<RoundedCardBackground style={[shadowStyle]}>
{children}
</RoundedCardBackground>
);
};
const styles = StyleSheet.create({
shadow: {
elevation: 2,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3,
},
shadowRadius: 10,
shadowOpacity: 0.05,
},
});
export default RoundedCard;

我试图测试一个简单的功能,但我收到了一个来自样式组件主题的错误。

这是我的测试:

import React from 'react';
import { Text } from '/components/atoms';
import { render } from '/utilities/testUtils';
import theme from '../../themes/primary';
import RoundedCard from './RoundedCard';
describe('RoundedCard', () => {
it('displays correct children', () => {
const { queryByText } = render(
<ThemeProvider theme={theme}>
<RoundedCard>
<Text>Test</Text>
</RoundedCard>,
</ThemeProvider>
);
expect(queryByText('Test')).not.toBeNull();
});
});

这是我得到的错误:

TypeError: Cannot read property 'white' of undefined
79 | export const RoundedCardBackground = styled.View`
80 |     flex-shrink: 1;
> 81 |     background-color: ${(props) => props.theme.colors.white};
|                                                       ^
82 |     border-radius: 6px;
83 |     overflow: hidden;
84 | `;

有什么东西我遗漏了吗?我原以为在ThemeProvider中封装组件就可以了,但仍然会出现错误。

仅供参考,这是抛出错误的样式组件

export const RoundedCardBackground = styled.View`
flex-shrink: 1;
background-color: ${(props) => props.theme.colors.white};
border-radius: 6px;
overflow: hidden;
`;

我遇到的问题的解决方案是更改

import { ThemeProvider } from 'styled-components';

import { ThemeProvider } from 'styled-components/native';

我认为Jest(或其他测试实用程序(找不到props.theme,因为主题是undefined。您必须将主题传递给您的组件。

import React from 'react';
import { Text } from '/components/atoms';
import { render } from '/utilities/testUtils';
import RoundedCard from './RoundedCard';
const theme = {
colors: {
white: "#fff"
}
}
describe('RoundedCard', () => {
it('displays correct children', () => {
const { queryByText } = render(
<ThemeProvider theme={theme}>
<RoundedCard>
<Text>Test</Text>
</RoundedCard>,
</ThemeProvider>
);
expect(queryByText('Test')).not.toBeNull();
});
});

最新更新