Can't get Jest to work with Styled Components which contain theming
Wrapping the ThemeProvider
around the component and passing the theme
object to it, works fine for me.
import React from 'react';
import { ThemeProvider } from 'styled-components';
import { render, cleanup } from '@testing-library/react';
import Home from '../Home';
import { themelight } from '../../Layout/theme';
afterEach(cleanup);
test('home renders correctly', () => {
let { getByText } = render(
<ThemeProvider theme={themelight}>
<Home name={name} />
</ThemeProvider>
);
getByText('ANURAG HAZRA');
})
I've managed to fix this problem with help of a colleague. I had another component extend the SlideTitle
component which broke the test:
const SlideSubtitle = SlideTitle.extend`
font-family: ${props =>
props.theme.LooksBrowser.SlideSubtitle.FontFamily};
`;
I refactored my code to this:
const SlideTitlesSharedStyling = styled.p`
flex: 0 0 auto;
text-transform: uppercase;
line-height: 1;
color: ${props => props.color};
font-size: ${PXToVW(52)};
`;
const SlideTitle = SlideTitlesSharedStyling.extend`
font-family: ${props => props.theme.LooksBrowser.SlideTitle.FontFamily};
`;
const SlideSubtitle = SlideTitlesSharedStyling.extend`
font-family: ${props => props.theme.LooksBrowser.SlideSubtitle.FontFamily};
`;
And my tests starting passing again!