React测试库:测试属性/属性

J. *_*ers 6 unit-testing typescript reactjs jestjs react-testing-library

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

我想编写一个单元测试,检查是否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");
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

但是此测试失败并显示:

? 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.
Run Code Online (Sandbox Code Playgroud)

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

小智 12

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

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');
})
Run Code Online (Sandbox Code Playgroud)

笔记:

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


Est*_*ask 7

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

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

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

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

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

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

那么它可以断言为:

  expect(getByTestId("grid-item")).toHaveClass("item");
Run Code Online (Sandbox Code Playgroud)


Ale*_*dze 6

我有一个不同的案例,但问题的标题把我带到了这里。因此,如果您想检查渲染的元素是否具有特定的属性值,您可以getAttribute在找到的元素上使用该方法:

  it('should have red fill', () => {
      const color = 'red';
      const { container } = render(<YourComponent color="red" />);

      expect(container.querySelector('your-selector').getAttribute('fill')).toBe(color);
  });
Run Code Online (Sandbox Code Playgroud)

更多信息在这里: https: //www.wilbertom.com/post/react-testing-library-testing-a-node-attribute/