typescript React 测试库:测试属性/道具

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53132820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:42:21  来源:igfitidea点击:

React testing library: Test attribute / prop

reactjstypescriptunit-testingjestjsreact-testing-library

提问by J. Hesters

I'm writing a React app using TypeScript. I use material-ui for my components and react-testing-library for my unit tests.

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

I'm writing a wrapper for material-ui's Grid component so that I always have an item.

我正在为 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);

I want to write a unit test that checks if item={true}. I tried to use the helper library jest-dom's toHaveAttributelike this:

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

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");
    });
  });
});

But this test fails with:

但是这个测试失败了:

● 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.

How can I test if an element has a certain attribute?

如何测试元素是否具有特定属性?

采纳答案by Estus Flask

jest-domtoHaveAttributeassertion asserts itemattributewhile the test tries to test itemprop.

jest-domtoHaveAttribute在测试尝试测试prop时断言断言item属性item

itemprop won't necessarily result in itemattribute, and since it's non-standard attribute it most probably won't.

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

react-testing-librarypropagates functional testing and asserts resulting DOM, this requires to be aware of how components work. As can be seen here, itemprops results in adding a class to grid element.

react-testing-library传播功能测试并断言结果 DOM,这需要了解组件的工作方式。从这里可以看出,itemprops 导致向网格元素添加一个类。

All units but tested one should be mocked in unit tests, e.g.:

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

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

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

Then it could be asserted as:

那么它可以断言为:

  expect(getByTestId("grid-item")).toHaveClass("item");