使用带有样式化组件和主题React Native的react-test-renderer 文本组件测试

问题描述

我有一个styled-component正在使用styled-system,并且运行良好,但是当我去测试组件时,似乎无法从主题中正确填充样式。 / p>

这很奇怪,因为如果我应用marginLeft={1}之类的道具,该样式将从Theme.space属性中正确翻译。这是color系统的专门问题吗?

文本组件

import React from 'react';
import styled from 'styled-components/native';
import {
  color,space,typography,variant,system,} from 'styled-system';

const textDecoration = system({ textDecoration: true });
const textDecorationColor = system({ textDecorationColor: true });
const textVariant = variant({ scale: 'text' });
const Text = styled.Text`
  ${textVariant}
  ${textDecoration}
  ${textDecorationColor}
  ${color} <-- using color system
  ${space}
  ${typography}
`;

export default Text;

测试

import React from 'react';
import renderer from 'react-test-renderer';
import { ThemeProvider } from 'styled-components';

import Text from '../src/atoms/Text';
import Theme from '../src/theme';

test('Text is referencing Theme (colors)',() => {
  console.log('Theme navy -->',Theme.colors.navy); // Theme navy --> #004175

  const tree = renderer
    .create(
      <ThemeProvider theme={Theme}>
        <Text color="navy" />
      </ThemeProvider>,).toJSON();
  const [styles] = tree.props?.style || {};

  console.log('Post-render color -->',styles.color); // Post-render color --> navy

  expect(styles.color).toBe(Theme.colors.navy);
});
npm run test
...
 ● Text is referencing Theme (colors)

    expect(received).toBe(expected) // Object.is equality

    Expected: "#004175"
    Received: "navy"
...

通常我会用color="primary"来测试#3592fb,但是我只是得到一个错误,指出primary对于样式属性color不是有效值,告诉我ThemeProvider工作不正常。

任何对此的帮助将不胜感激! 谢谢

解决方法

经过further googling的使用后,事实证明我应该使用styled-components/native中的ThemeProvider。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...