React 测试库:测试属性/prop

2024-04-28

我正在使用 TypeScript 编写一个 React 应用程序。我使用material-ui作为我的组件,使用react-testing-library作为我的单元测试。

我正在为 Material-ui 的 Grid 组件编写一个包装器,以便我始终拥有一个项目。

import Grid from "@material-ui/core/Grid";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import React, { PureComponent } from "react";
import styles from "./styles";

export interface OwnProps {
  className?: string;
}

export interface Props extends WithStyles<typeof styles>, OwnProps {}

export interface DefaultProps {
  className: string;
}

export class GridItem extends PureComponent<Props & DefaultProps> {
  static defaultProps: DefaultProps = {
    className: ""
  };

  render() {
    const { classes, children, className, ...rest } = this.props;
    return (
      <Grid
        data-testid="grid-item"
        item={true}
        {...rest}
        className={classes.grid + " " + className}
      >
        {children}
      </Grid>
    );
  }
}

export default withStyles(styles)(GridItem);

我想编写一个单元测试来检查是否item={true}。我尝试使用辅助库 jest-dom'stoHaveAttribute像这样:

import "jest-dom/extend-expect";
import React from "react";
import { cleanup, render } from "react-testing-library";
import GridItem, { OwnProps } from "./GridItem";
afterEach(cleanup);

const createTestProps = (props?: object): OwnProps => ({
  ...props
});

describe("Parallax", () => {
  const props = createTestProps();
  const { getByTestId } = render(<GridItem {...props} />);
  describe("rendering", () => {
    test("it renders the image", () => {
      expect(getByTestId("grid-item")).toHaveAttribute("item", "true");
    });
  });
});

但这个测试失败了:

● GridItem › rendering › it renders the image

    expect(element).toHaveAttribute("item", "true") // element.getAttribute("item") === "true"

    Expected the element to have attribute:
      item="true"
    Received:
      null

      14 |   describe("rendering", () => {
      15 |     test("it renders the image", () => {
    > 16 |       expect(getByTestId("grid-item")).toHaveAttribute("item", "true");
         |                                        ^
      17 |     });
      18 |   });
      19 | });

      at Object.toHaveAttribute (src/components/Grid/GridItem/GridItem.test.tsx:16:40)

Test Suites: 1 failed, 3 passed, 4 total
Tests:       1 failed, 3 passed, 4 total
Snapshots:   0 total
Time:        1.762s, estimated 2s
Ran all test suites related to changed files.

如何测试一个元素是否具有某个属性?


jest-dom toHaveAttribute断言断言item 属性当测试尝试测试时item prop.

itemprop 不一定会导致item属性,并且由于它是非标准属性,因此很可能不会。

react-testing-library传播功能测试并断言生成的 DOM,这需要了解组件如何工作。可以看出here https://github.com/mui-org/material-ui/blob/v3.3.2/packages/material-ui/src/Grid/Grid.js#L220, itemprops 会导致向网格元素添加一个类。

除了测试单元之外的所有单元都应该在单元测试中进行模拟,例如:

...
import GridItem, { OwnProps } from "./GridItem";

jest.mock("@material-ui/core/Grid", () => ({
  default: props => <div data-testid="grid-item" className={props.item && item}/>
}));

那么它可以被断言为:

  expect(getByTestId("grid-item")).toHaveClass("item");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 测试库:测试属性/prop 的相关文章

随机推荐

  • 如何删除 R 中字符向量中字符串的公共部分?

    假设一个字符向量如下 file1 p1 analysed samples txt file1 p1 raw samples txt f2 file2 p1 analysed samples txt f3 file3 p1 raw sampl
  • ReportViewer控件加载指示器?

    是否可以更改 ReportViewer 控件的图像 绿色旋转的东西 目前我正在隐藏它并重叠进度条 这是 WinForms 而不是 ASP 控件 似乎有点啰嗦 Thanks 好吧 我的朋友 你给了我一个挑战 但我想出了如何做到这一点 这是我用
  • 有没有一种简单的方法可以将我的苹果应用程序转换为安卓应用程序?

    我是一名应用程序开发人员 我使用 Xcode 来开发我的所有应用程序 但看到当今市场上很多人都拥有非苹果设备 所以我想我想知道是否有一种简单的方法可以将我的苹果应用程序代码转换为Android格式 以便我可以提交到两个市场 Android
  • 在 systemd 服务文件内/内联添加 shell 命令

    我正在运行gunicorn通过 systemd 将服务器作为服务 这是示例service file Unit Description Gunicorn NGINX After network target Service User root
  • Curl下载到HDFS

    我有这个代码 curl o fileName csv url xargs hdfs dfs moveFromLocal 1 somePath 当我执行此代码时 curl 将请求中的值放入 fileName csv 中 该文件将移动到 HDF
  • 如何在小部件中使用列表视图? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在尝试创建一个从 rss feed 加载到小部件中的列表视图 有谁知道如何在小部件中使用列表视图的教
  • 学习 BDD、TDD(ruby、C#、javascript)的好资源

    学习 BDD 和 TDD ruby C javascript 有哪些好的资源 现在用什么好的框架 See 为什么我应该练习测试驱动开发以及应该如何开始 https stackoverflow com questions 4303 why s
  • 使用VBA抓取实时数据

    我想从中抓取实时数据https iboard ssi com vn bang gia hose https iboard ssi com vn bang gia hose使用VBA 我的代码如下 但它不会返回其中包含数据的 html 文件
  • 什么是依赖注入的 Pythonic 方式?

    介绍 对于 Java 依赖注入作为纯 OOP 工作 即您提供要实现的接口 并在框架代码中接受实现定义的接口的类的实例 现在对于 Python 您可以执行相同的操作 但我认为该方法对于 Python 而言开销太大 那么如何以 Pythonic
  • Swashbuckle IDocumentFilter 实现 - 如何将 ActionDescriptor.MethodInfo 链接到操作

    项目 ASP Net Core 2 2 Web API 软件包 Swashbuckle AspNetCore 4 0 1 我正在写一个实现Swashbuckle AspNetCore SwaggerGen IDocumentFilter它在
  • 缓慢的 data.frame 行分配

    我正在使用 RMongoDB 需要用查询的值填充空的 data frame 结果相当长 大约有 200 万个文档 行 当我进行性能测试时 我发现将值写入行的时间随着数据帧的维度的增加而增加 也许这是一个众所周知的问题 而我是最后一个注意到它
  • 当元素被覆盖时取消 mouseout 事件

    希望这个 JSFiddle 能比我的话更好地说明这个问题 http jsfiddle net pmwRc 6 http jsfiddle net pmwRc 6 当地图悬停时 我在图像地图上显示绝对定位的 H4 作为标签 但是 当鼠标指针移
  • $.fn.function 的调用函数

    问题如下 有一个函数自定义 jquery 函数 里面有另一个函数 例如 fn slides function args function foo args 我现在的问题是 我如何调用方法 foo foo不是一种方法 这是一个本地函数 除非您
  • 字符串等于和 == 与字符串连接[重复]

    这个问题在这里已经有答案了 我试图理解字符串连接与字符串比较的输出 需要明确的是 我有一个类使用 和 equals 来比较两个字符串 我试图将 和 equals 的输出连接到一个字符串 equals 的输出是 concats 但是 的输出是
  • Android Fragment onCreateView 与 onActivityCreated

    我知道片段的视图层次结构必须在 onCreateView 中膨胀 但是 onCreateView 中还可以包含哪些其他功能 而不是应该等待 onActivityCreated 我当前的实现对所有内容都使用单独的活动 典型的活动在其 onCr
  • PHP 路由 - 样式表无效

    我用 PHP 创建了一个基本的路由系统 url 被分割成一个数组 这样我就可以根据 URL 决定显示什么 例如 www domain com page option param 因此 在我的index php 中 我为页眉 内容和页脚定义了
  • 如何在触摸时旋转图像并将图像拖动到另一个图像上

    我正在开发一个应用程序 我需要一个包含许多图像的图库 我想要做的是 当用户点击 单击任何图像时 它应该将该图像旋转到 90 度 如果用户将任何图像拖动到任何其他图像的顶部 那么这些图像应该交换它们的位置 或者我们可以说交换 彼此的位置 解释
  • UITableView:使用 moveRowAtIndexPath:toIndexPath: 和 reloadRowsAtIndexPaths:withRowAnimation: 一起出现损坏

    我想使用 iOS 5 漂亮的行移动调用来为表格视图设置动画以匹配某些模型状态更改 而不是旧式的删除和插入 更改可能包括重新排序和就地更新 并且我想对两者进行动画处理 因此某些行需要reloadRowsAtIndexPaths But UIT
  • 在 Python/Pandas 中执行不同操作的许多列上有条件地聚合分组数据

    考虑以下简化的示例数据帧df Department CustomerID Date Price MenswearDemand HomeDemand 0 Menswear 418089 2019 04 18 199 199 0 1 Mensw
  • React 测试库:测试属性/prop

    我正在使用 TypeScript 编写一个 React 应用程序 我使用material ui作为我的组件 使用react testing library作为我的单元测试 我正在为 Material ui 的 Grid 组件编写一个包装器