我是测试的新手,所以我试图将酶添加到我的一个项目中。我的问题是使用find()
时,ShallowWrapper为空。另外,我正在使用Material UI,所以我不知道这是否是问题的一部分。
我正在测试的组件
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
const styles = theme => ({
root: {
flexGrow: 1
},
background: {
backgroundColor: "#2E2E38"
},
title: {
color: "#FFE600",
flexGrow: 1
}
});
const NavBar = ({ classes }) => {
return (
<div className={classes.root} data-test="nav-bar">
<AppBar className={classes.background}>
<Toolbar>
<Typography variant="h5" className={classes.title}>
App
</Typography>
</Toolbar>
</AppBar>
</div>
);
};
export default withStyles(styles)(NavBar);
测试
import React from "react";
import { shallow } from "enzyme";
import NavBar from "./NavBar";
describe("NavBar component", () => {
it("Should render without errors.", () => {
let component = shallow(<NavBar />);
let navbar = component.find("data-test", "nav-bar");
console.log("Log is", component);
expect(navbar).toBe(1);
});
});
答案 0 :(得分:1)
尝试将find(selector)
中的selector更改为以下内容,以data-test="nav-bar"
为目标元素。您可能需要使用dive()才能访问样式组件的内部组件:
import React from "react";
import { shallow } from "enzyme";
import NavBar from "./NavBar";
describe("NavBar component", () => {
it("Should render without errors.", () => {
const component = shallow(<NavBar />);
// Use dive() to access inner components
const navbar = component.dive().find('[data-test="nav-bar"]');
// Test that we found a single element by targeting length property
expect(navbar.length).toBe(1);
});
});
如果愿意,还可以使用对象语法:
const navbar = component.find({'data-test': 'nav-bar'});
除了使用dive()
之外,您也可以使用mount()
组件代替shallow()
,但这取决于您的用例:
import React from "react";
import { mount } from "enzyme";
import NavBar from "./NavBar";
describe("NavBar component", () => {
it("Should render without errors.", () => {
const component = mount(<NavBar />);
// Use dive() to access inner components
const navbar = component.find('[data-test="nav-bar"]');
// Test that we found a single element by targeting length property
expect(navbar.length).toBe(1);
});
});
希望有帮助!
答案 1 :(得分:0)
由于另一个原因,我找不到这个SingleDatePicker元素而遇到了这个问题。文档中的示例2。文档中的React Component构造函数为我修复了该问题。
https://enzymejs.github.io/enzyme/docs/api/selector.html#1-a-valid-css-selector
使用
wrapper.find(SingleDatePicker).prop('onDateChange')(now);
代替
wrapper.find('SingleDatePicker').prop('onDateChange')(now);
是我的把戏。