0

我有一个简单的组件:

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;

我正在尝试测试一个简单的功能,但我收到了来自 styled-components 主题的错误。

这是我的测试:

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;
`;
4

2 回答 2

0

我遇到的问题的解决方案正在改变

import { ThemeProvider } from 'styled-components';

import { ThemeProvider } from 'styled-components/native';
于 2021-06-01T20:03:05.680 回答
0

我认为 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();
    });
});
于 2021-04-19T19:35:08.163 回答