Using react-test-renderer w/ styled-components & Theme (React Native)

1.5k views Asked by At

I have a styled-component that is using styled-system and it is working perfectly but when i go to test the component i can't seem to get it to populate the styles correctly from the Theme.

It's strange because if i apply a prop like marginLeft={1} this style gets correctly translated from the Theme.space property. Is this an issue with the color system specifically?

Text component

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;

test

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"
...

Normally i'd test with color="primary" which is #3592fb but i just get an error stating that primary is not a valid value for the style-property color which tells me that the ThemeProvider is not working correctly.

Any help with this would be greatly appreciated! Thank you

1

There are 1 answers

0
Francis Leigh On

After a bit of further googling it turns out i should be using the ThemeProvider from styled-components/native

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