Reactjs 反应测试库:测试子项是否正确通过/呈现
我正在用TypeScript编写一个React应用程序。我的组件使用MaterialUI,单元测试使用react测试库 我正在为MaterialUI的网格组件编写一个包装器,以便始终有一个容器Reactjs 反应测试库:测试子项是否正确通过/呈现,reactjs,typescript,unit-testing,jestjs,react-testing-library,Reactjs,Typescript,Unit Testing,Jestjs,React Testing Library,我正在用TypeScript编写一个React应用程序。我的组件使用MaterialUI,单元测试使用react测试库 我正在为MaterialUI的网格组件编写一个包装器,以便始终有一个容器 import Grid from "@material-ui/core/Grid"; import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"; import React, { PureComponent }
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 GridContainer extends PureComponent<Props & DefaultProps> {
static defaultProps: DefaultProps = {
className: ""
};
render() {
const { classes, children, className, ...rest } = this.props;
return (
<Grid
data-testid="grid-container"
container={true}
{...rest}
className={classes.grid + " " + className}
>
{children}
</Grid>
);
}
}
export default withStyles(styles)(GridContainer);
是否无法为渲染函数中的元素提供数据测试ID?我如何测试子对象是否正确渲染
编辑
以下是调试的输出:
● Console
console.log node_modules/react-testing-library/dist/index.js:57
<body>
<div>
<div
class="MuiGrid-container-2 GridContainer-grid-1 "
data-testid="grid-container"
>
<div
data-testid="child"
/>
</div>
</div>
</body>
● 安慰
console.log node_modules/react testing library/dist/index.js:57
问题是在描述
块中渲染一次。这可能不符合你的想法。描述块中不在测试中的代码(或其他jest函数,如每个之前的)通过jest提前运行。通常,您不希望任何代码位于descripe
块内,而在test
(或其他jest函数)外
可以在每次测试之前在中渲染组件,也可以在每次测试中调用渲染辅助函数
我用上述方法在这里创建了您的沙箱,现在两个测试都通过了:您尝试做的应该是可能的。你能试着记录下@Gpx的输出吗?@Gpx我编辑了命令并发布了输出。div就在那里!很奇怪。你能试着在codesandbox上发布代码吗?@gpx当然,在这里:。我还包括了我目前使用的变通方法。
● GridContainer › rendering › it renders it's children
Unable to find an element by: [data-testid="child"]
<body />
24 | test("it renders it's children", () => {
25 | expect(container.children.length).toBe(1);
> 26 | expect(getByTestId("child")).toBeDefined();
| ^
27 | });
28 | });
29 | });
at getElementError (node_modules/dom-testing-library/dist/query-helpers.js:30:10)
at getAllByTestId (node_modules/dom-testing-library/dist/queries.js:231:45)
at firstResultOrNull (node_modules/dom-testing-library/dist/query-helpers.js:38:30)
at getByTestId (node_modules/dom-testing-library/dist/queries.js:241:42)
at Object.getByTestId (src/components/Grid/GridContainer/GridContainer.test.tsx:26:14)
● Console
console.log node_modules/react-testing-library/dist/index.js:57
<body>
<div>
<div
class="MuiGrid-container-2 GridContainer-grid-1 "
data-testid="grid-container"
>
<div
data-testid="child"
/>
</div>
</div>
</body>