Can't Get Jest To Work With Styled Components Which Contain Theming
The Problem I've been using Jest and Enzyme to write tests for my React components build with the awesome Styled Components library. However, since I've implemented theming all my
Solution 1:
Wrapping the ThemeProvider
around the component and passing the theme
object to it, works fine for me.
importReactfrom'react';
import { ThemeProvider } from'styled-components';
import { render, cleanup } from'@testing-library/react';
importHomefrom'../Home';
import { themelight } from'../../Layout/theme';
afterEach(cleanup);
test('home renders correctly', () => {
let { getByText } = render(
<ThemeProvidertheme={themelight}><Homename={name} /></ThemeProvider>
);
getByText('ANURAG HAZRA');
})
Solution 2:
I've managed to fix this problem with help of a colleague. I had another component extend the SlideTitle
component which broke the test:
constSlideSubtitle = SlideTitle.extend`
font-family: ${props =>
props.theme.LooksBrowser.SlideSubtitle.FontFamily};
`;
I refactored my code to this:
constSlideTitlesSharedStyling = styled.p`
flex: 0 0 auto;
text-transform: uppercase;
line-height: 1;
color: ${props => props.color};
font-size: ${PXToVW(52)};
`;
constSlideTitle = SlideTitlesSharedStyling.extend`
font-family: ${props => props.theme.LooksBrowser.SlideTitle.FontFamily};
`;
constSlideSubtitle = SlideTitlesSharedStyling.extend`
font-family: ${props => props.theme.LooksBrowser.SlideSubtitle.FontFamily};
`;
And my tests starting passing again!
Post a Comment for "Can't Get Jest To Work With Styled Components Which Contain Theming"