【问题标题】:React testing library: Test attribute / propReact 测试库:测试属性/prop
【发布时间】:2019-04-07 12:56:30
【问题描述】:

我正在使用 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 的 toHaveAttribute

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.

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

【问题讨论】:

  • 一个地方是(getByTestId("grid-item"),另一个地方是(getByTestId("item")。我想这是问题中的错字。
  • @estus 是 :)

标签: reactjs typescript unit-testing jestjs react-testing-library


【解决方案1】:

jest-domtoHaveAttribute 断言断言item 属性,而测试尝试测试item prop

item 属性不一定会导致 item 属性,因为它是非标准属性,所以很可能不会。

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

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

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

【讨论】:

  • 同样的错误信息。它仍然说它得到了null
  • ● GridItem › rendering › it is an item expect(element).toHaveAttribute("item") // element.hasAttribute("item") Expected the element to have attribute: item Received: null 是出现的错误信息。如何测试元素是否具有item=true属性?
  • 我明白了。断言消息具有误导性。 null 表示根本没有属性。问题是它没有item 属性。我更新了答案以解释这一点。如果你想测试实际代码(例如 props)而不是它对 DOM 的影响,我建议切换到 Enzyme。
【解决方案2】:

如果有人仍然遇到这个问题,我会这样解决:

it('Check if it is a materialUI Grid item', () => {
    //Rendering the component in a constant.
    const { container } = render(<YourComponent />); 
    //Accessing the grid wrapper. In this case by the attribute you provided.
    const grid = container.querySelector('[data-testid="grid-item"]'); 
    //What we are expecting the grid to have.  
    expect(grid).toHaveClass('MuiGrid-item');
})

注意事项:

  1. 我注意到在代码项中它被声明为字符串而不是布尔值:item='true',这将在您运行测试时触发警告。 item={true} 是正确的声明方式。实际上,在材质 UI 中,当您在网格中编写 item 时,默认情况下它当然是 true,在我看来是没有必要的。
  2. item 是材料 UI Grid 中的一个类,正如前面的答案正确建议的那样。因此,在这种情况下,正确的类名应该是“MuiGrid-item”。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2021-08-23
    • 2021-02-20
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2020-10-06
    • 2015-08-17
    相关资源
    最近更新 更多