【发布时间】:2021-01-27 20:58:59
【问题描述】:
我有一个使用styled-system 的styled-component,它运行良好,但是当我去测试组件时,我似乎无法让它从主题中正确填充样式。
这很奇怪,因为如果我应用像 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 是无法正常工作。
对此的任何帮助将不胜感激! 谢谢
【问题讨论】:
标签: reactjs jestjs styled-components react-test-renderer styled-system