简体   繁体   English

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

[英]React testing library: Test attribute / prop

I'm writing a React app using TypeScript.我正在使用 TypeScript 编写 React 应用程序。 I use material-ui for my components and react-testing-library for my unit tests.我对组件使用 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} .我想编写一个单元测试来检查item={true} I tried to use the helper library jest-dom's toHaveAttribute like this:我尝试像这样使用辅助库 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");
    });
  });
});

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?如何测试元素是否具有特定属性?

jest-dom toHaveAttribute assertion asserts item attribute while the test tries to test item prop . jest-dom toHaveAttribute断言在测试尝试测试item prop时断言item属性

item prop won't necessarily result in item attribute, and since it's non-standard attribute it most probably won't. item prop 不一定会导致item属性,并且由于它是非标准属性,因此很可能不会。

react-testing-library propagates functional testing and asserts resulting DOM, this requires to be aware of how components work. react-testing-library传播功能测试并断言结果 DOM,这需要了解组件的工作方式。 As can be seen here , item props results in adding a class to grid element.这里可以看出, item props 导致向网格元素添加一个类。

All units but tested one should be mocked in unit tests, eg:除了测试单元之外的所有单元都应该在单元测试中模拟,例如:

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

If someone is still having this issue I solved it this way:如果有人仍然遇到这个问题,我是这样解决的:

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

Notes:笔记:

  1. I noticed that in the code item it's been declared as a string and not as a boolean: item='true', which will trigger a warning when you run the test.我注意到在代码项中它被声明为字符串而不是布尔值:item='true',这将在您运行测试时触发警告。 item={true} is the correct way of declaring it. item={true} 是正确的声明方式。 Actually in material UI when you write item inside a grid its of course by default true, in my opinion is not necessary.实际上,在材质 UI 中,当您在网格中编写项目时,默认情况下它当然是 true,在我看来没有必要。
  2. item is a class inside material UI Grid as the previous answer correctly suggested. item 是 Material UI Grid 中的一个类,正如前面的答案正确建议的那样。 So by that the correct class name should be refered in this case is 'MuiGrid-item'.因此,在这种情况下应该引用正确的类名是“MuiGrid-item”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 React 测试库测试作为道具传递给孩子的函数? - How to test a function passed as a prop to child using React Testing Library? 如何使用 react-testing-library 对数组作为 prop 进行单元测试 - How to unit test an array as a prop using react-testing-library 如何使用 React-testing-library 测试 styled-components 属性? - How to test styled-components attribute with React-testing-library? React 测试库 - 如何发送“anchorEl”作为道具? - React testing library - how to send “anchorEl” as prop? 使用 testing-library/react-native 接收号码的测试道具 - test prop that's receiving number with testing-library/react-native 如何使用@testing-library/user-event 版本 14 在 React 中测试 `onKeyDown` 道具? - How can I test `onKeyDown` prop in React with @testing-library/user-event version 14? 使用 react-testing-library 和 jest 测试是否调用了 prop 函数 - Testing if a prop function was called using react-testing-library and jest 使用React Testing库在React中声明表单提交的道具调用 - Asserting prop call for form submit in React using React Testing Library 当使用 React 测试库更改数据属性时,如何编写一个测试用例来验证 function 是否被正确调用? - How can I write a test case that verifies that the function is being called correctly when the data prop changes using React Testing Library? 如何在 react-testing-library 中访问 prop 值 - How to access prop value in react-testing-library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM