【问题标题】:unit testing material ui components with jest用玩笑对材料 ui 组件进行单元测试
【发布时间】:2019-07-08 09:24:24
【问题描述】:

material ui 中有一个网格组件,我希望在我的 React 应用程序中使用 jest 对其进行单元测试。请在下面找到我的代码

对于上面的代码,我们将如何编写单元测试呢?我浏览了他们的测试指南https://material-ui.com/guides/testing,但不清楚。任何想法/建议都非常感谢

import React from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";

import "./styles.scss";

const styles = theme => ({
    root: {
      flexGrow: 1
    },
    paper: {
      height: 140,
      width: 100
    }
});

function Space({ classes }) {
  const x = [1, 2, 3];

  return (
    <div className="center">
      <Grid container className={classes.root}>
        <Grid item xs={12}>
          <Grid container justify="center" spacing={Number(32)}>
            {x.map(value => (
              <Grid key={value} item>
                <Paper className={classes.paper} />
              </Grid>
            ))}
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
}

我应该能够使用 jest 对上述代码进行单元测试

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    人们可能会因为我这么说而讨厌我。由于这个案例不包含任何逻辑,我将只导出函数,设置反映真实数据的道具,并为您的浅渲染函数制作快照。

    每当它发生变化时,请在更新之前检查它,一切正常。

    编辑:在没有 withStyles HOC 的情况下导出普通组件并将类添加到您的模拟道具中。 另一个编辑:

    在这种情况下,您的测试可能看起来像这样:

    describe('SpaceComponent', () => {
      it('it renders the component correctly', () => {
        const props = { classes: { root: 'root', paper: 'paper' } };
        const component = shallow(<Space {...props} />);
        expect(component).toMatchSnapshot();
      });
    });
    

    【讨论】:

    • 您好,感谢您的解决方案,请问有伪代码吗?这对我来说是新事物
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-11-29
    • 2023-02-26
    • 2015-06-28
    • 2021-10-22
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多