Material-UI自定义主题调色板属性在Jest中产生“未定义”错误
简而言之,我正在使用 Jest、React 测试库和 Material UI createMuiTheme,除测试外,一切正常。只有当我从createMuiTheme.
我正在为我的 MUI 项目创建一个自定义主题,如下所示:
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);
我的组件样式在 JSS 中定义如下:
const useStyles = makeStyles((theme) => {
return {
ctaCopy: {
color: theme.extraColors.activeButton,
},
};
});
我认为组件本身并不重要,但它看起来像这样:
<Link className={classes.ctaCopy} href={ctaUrl}>
{ctaCopy}
</Link>
这有效。组件在呈现时正确显示,具有预期的颜色。然而,当我在 Jest 测试中使用这个组件时,它失败了,说:
TypeError: Cannot read property 'activeButton' of undefined
更新:
我进一步挖掘并尝试了其他一些解决方案,包括使用MuiThemeProvider和ThemeProvider(当然,单独使用)。为了做到这一点,我过去常常import引入我的自定义主题,该主题托管在外部库中。如下:
import { defaultTheme } from 'my-external-lib';
这同样适用于呈现的页面。我什至到console.log了defaultTheme并且它再次在呈现的页面中正确打印。但是,在测试中,如果我console.log(defaultTheme)结果未定义!!
所以也许更新的问题细微差别是,为什么我不能import以这种方式与 Jest/React 测试库一起使用?
这可能需要发布一个全新的问题。
到目前为止我尝试过的更多内容:
// 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();
});
});
为什么我只在测试中收到这个错误?