0

我 在我的反应网络应用程序中使用材料 UI 。我想用 jest 测试我的组件,以将样式保存在组件的快照中,就像jest-styled-component对 styled-component 所做的那样,但我不能。

您可以在代码和框中看到我的示例项目, 但这里是重要部分:我使用create-react-app使用以下命令创建我的项目:

npx create-react-app myapp

这是我的 index.js 文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {MuiThemeProvider} from '@material-ui/core/styles';
import theme from './customTheme';
ReactDOM.render(
    <MuiThemeProvider theme={theme}>
        <App/>
    </MuiThemeProvider>,
    document.getElementById('root')
);

这是我在 src 文件夹中的 customTheme.js 文件:

import {createMuiTheme} from '@material-ui/core/styles';
const theme = createMuiTheme({
    typography: {
        fontFamily: [
            'Roboto',
            '"Segoe UI"',
            '"Helvetica Neue"',
            'Arial',
            'sans-serif',
            '"Apple Color Emoji"',
            '"Segoe UI Emoji"',
            '"Segoe UI Symbol"',
        ].join(','),
    },
    palette: {
        color: 'blue',
    }
});
export default theme;

这是我要测试的 App.js:

import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
export const styles = theme => ({
    mystyle: {
        fontFamily: theme.typography.fontFamily,
        border: '1px solid green',
        background: 'yellow',
        color: theme.palette.color,
    },
});
function MyComponent(props) {
    const {classes} = props;
    return (
        <div>
            <p className={classes.mystyle}> my text </p>
            <Button className={classes.mystyle}>my button</Button>
        </div>
    );
}
MyComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(MyComponent);

请注意,我正在用 JSS 覆盖样式,并且我有自己的主题。我想从组件中获取快照,使 css 成为快照的一部分,例如来自 github 中 material-UI 存储库的这个问题,或者像 jest-styled-component-do 对 styled-component 所做的那样。为了实现这个目标,我在 demo.test.js 中编写了这段代码:

import React from "react";
import renderer from "react-test-renderer";
import App from '../App';
import {styles} from '../App';
describe("snapshot test", () => {
    it("should match snapshot", () => {
        const wrapper = renderer
            .create(<App classes={styles}/>)
            .toJSON();
        expect(wrapper).toMatchSnapshot();
    });
});

但是通过这个测试,我的样式不在快照中,因此如果我在 App 组件中更改 mystyle,快照测试将不会失败。我已经阅读了以下资源,但无法得到我想要的: https ://github.com/mui-org/material-ui/issues/9492 https://github.com/mui-org/material-ui/issues /6834

感谢您的任何反馈

4

0 回答 0