【问题标题】:Styled-components theme with react-native testing-library带有 react-native 测试库的样式化组件主题
【发布时间】:2021-08-06 18:40:53
【问题描述】:

我已经被困了一段时间,试图弄清楚我在这里做错了什么,我觉得我已经尝试了我找到的所有解决方案,但它不起作用。为了描述正在发生的事情,我制作了最简单的组件来展示正在发生的事情。

这是我的主题

export default const theme = {
    colors: {
        white: '#FFFFFF',
        black: '#000',
        lightGray: '#f0f2f1',
        darkGray: '#909190',
        primaryColor: '#007772',
        secondaryColor: '#0775BC',
        textColor: '#231F20',
        lightPrimary: '#DBFFFF',
        red: '#B80F0A',
        primaryHalf: '#7FBAB8',
    },
    font: {
        family: 'Nunito-Regular',
    },
};

这是我的组件

import React from 'react';
import styled from 'styled-components/native';

const Wrapper = styled.View`
    background-color: ${(props) => props.theme.colors.white};
`;

const TestSimpleComponent: React.FC = ({ children }) => {
    return <Wrapper>{children}</Wrapper>;
};

export default TestSimpleComponent;

很简单,只是用来自主题的白色背景包裹一些东西。

最后,这是我的简单测试

import React from 'react';
import { Text } from 'react-native';
import { render } from '@testing-library/react-native';

import TestSimpleComponent from './TestSimpleComponent';
import { ThemeProvider } from 'styled-components';
import theme from '../../themes/primary';

describe('TestSimpleComponent', () => {
    it('displays correct children', () => {
        const { queryByText } = render(
            <ThemeProvider theme={theme}>
                <TestSimpleComponent>
                    <Text>Test</Text>
                </TestSimpleComponent>
            </ThemeProvider>,
        );
        expect(queryByText('Test')).not.toBeNull();
    });
});

这是抛出的错误。基本上是说主题提供者出于某种我似乎无法弄清楚的原因没有将主题传递给组件。

TypeError: Cannot read property 'white' of undefined

      3 | 
      4 | const Wrapper = styled.View`
    > 5 |     background-color: ${(props) => props.theme.colors.white};
        |                                                       ^
      6 | `;
      7 | 
      8 | const TestSimpleComponent: React.FC = ({ children }) => {

我觉得我已经尝试了我在这里发现的所有问题,但似乎没有任何效果。唯一有效的是我手动将主题传递给 Wrapper,这不是一个可行的解决方案,因为我有一个大型应用程序,它在所有地方都使用样式组件中的主题。

我之前使用颜色文件时所有的测试都通过了,但是一旦我将它切换到主题,一切都坏了

我也尝试了所有被引用的 here

有谁知道我可能做错了什么?

【问题讨论】:

    标签: reactjs typescript react-native styled-components react-native-testing-library


    【解决方案1】:

    以防万一有人想知道答案是什么。 我遇到的问题的解决方案正在改变

    import { ThemeProvider } from 'styled-components';
    

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

    【讨论】:

    • 谢谢!事实证明我遇到了完全相同的问题。
    • 天哪,我用其他解决方案浪费了两天时间,我不知道我是怎么错过的。谢谢。
    猜你喜欢
    • 2018-03-24
    • 2021-01-27
    • 2021-06-14
    • 2019-02-16
    • 2021-11-16
    • 2018-09-26
    • 2021-09-06
    • 2017-05-16
    • 2021-11-25
    相关资源
    最近更新 更多