我正在使用TypeScript编写一个React应用程序。我使用material-ui作为组件,react-testing-library作为单元测试。
我正在为material-ui的Grid组件编写一个 Package 器,这样我就总是有一个项目。
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.
如何测试一个元素是否具有某个属性?
3条答案
按热度按时间5fjcxozz1#
jest-dom
toHaveAttribute
Assert在测试尝试测试item
prop 时Assertitem
* attribute*。item
prop不一定会导致item
属性,而且由于它是非标准属性,因此很可能不会。react-testing-library
传播功能测试并Assert结果DOM,这需要了解组件如何工作。从这里可以看出,item
props导致向网格元素添加一个类。除了测试过的单元之外,所有单元都应该在单元测试中模拟,例如:
然后可以Assert为:
mlmc2os52#
如果有人仍然有这个问题,我这样解决:
注意事项:
1.我注意到在代码项中,它被声明为字符串而不是布尔值:item ='true',这将在运行测试时触发警告。item={true}是正确的声明方式。实际上,在Material UI中,当你在网格中写入 item 时,默认情况下它当然是true,在我看来是没有必要的。
ecr0jaav3#
我有一个不同的案例,但问题的标题把我带到了这里。所以,如果你想检查一个呈现的元素是否有一个特定的属性值,你可以在找到的元素上使用
getAttribute
方法:更多信息:https://www.wilbertom.com/post/react-testing-library-testing-a-node-attribute/