In short, I'm using Jest, React Testing Library, and Material UI createMuiTheme
and everything works except for the tests. They break only when I add the custom theme from my compound theme from createMuiTheme
.
I'm creating a custom theme for my MUI project as follows:
import { createMuiTheme } from '@material-ui/core/styles';
export const theme = {
palette: {
extra: {
activeButton: '#D4564E',
black: '#000000',
darkGrey: '#232323',
rgbaInvisible: 'rgba(0, 0, 0, 0)',
success: '#4CAF50',
white: '#FFFFFF',
},
},
};
export default createMuiTheme(theme);
My component styles are defined in JSS like this:
const useStyles = makeStyles((theme) => {
return {
ctaCopy: {
color: theme.extraColors.activeButton,
},
};
});
The component itself I don't think is important but it looks like this:
<Link className={classes.ctaCopy} href={ctaUrl}>
{ctaCopy}
</Link>
This works. The component displays properly when rendered, with the expected colors. However, when I use this component in a Jest test, it fails, saying:
TypeError: Cannot read property 'activeButton' of undefined
Update:
I dug a little further and attempted a few other solutions, including using MuiThemeProvider
and ThemeProvider
(separately, of course). In order to do this, I used import
to pull in my custom theme, which is hosted in an external library. As follows:
import { defaultTheme } from 'my-external-lib';
This, again, works on a rendered page. I went so far as to console.log
the defaultTheme
and it prints correctly, again, in the rendered page. However, in the tests, if I console.log(defaultTheme)
the result is undefined!!
So perhaps the updated question nuance is, why can't I use import
in this way with Jest/React Testing Library?
This may warrant a whole new question being posted.
More of what I've tried so far:
// This theme created as above
import { ThemeProvider } from '@material-ui/core';
import { defaultTheme } from '@my-external-lib';
import MyComponent from './MyComponent';
const setupComponent = ({
ctaCopy,
ctaUrl,
} = {}) => {
render(
<ThemeProvider theme={defaultTheme}>
<MyComponent
ctaCopy={ctaCopy}
ctaUrl={ctaUrl}
/>
</ThemeProvider>,
);
};
const testCtaCopy = 'test-cta-copy';
const testCtaUrl = 'https://www.test.com';
describe('My component', () => {
it('should render', () => {
expect.assertions(1);
setupComponent({ ctaCopy: testCtaCopy, ctaUrl: testCtaUrl });
expect(screen.getByText(testCtaCopy)).toBeInTheDocument();
});
});
Why am I getting this error in tests only?
I encountered this today, the solution that fixed for me is this
const useStyles = makeStyles((theme) => {
return {
ctaCopy: {
color: theme.extraColors?.activeButton,
},
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With