使用 Enzyme 检查子元素的 class
Check class of child element using Enzyme
我正在尝试检查子元素的 class:
import React from "react";
import { shallow, } from "enzyme";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
function Bar() {
return <div className="Bar" />;
}
function Component() {
return (
<div className="root">
<Bar />
</div>
);
}
describe("foo", () => {
it("should", () => {
const wrapper = shallow(<Component />);
console.log(wrapper.hasClass("root"));
console.log(
wrapper
.children()
.first()
.hasClass("Bar")
);
});
});
它打印 true
和 false
。为什么第二个 hasClass
returns false
?
这是一个demo
更新:
.html()
returns 所有元素这一事实具有误导性,我认为 shallow
实际上呈现了所有内容。
应该是
wrapper
.childAt(0)
.dive()
.hasClass("Bar")
如果您 mount
您的组件必须先渲染它才能工作:
const w = mount(<Component />).render();
expect(w.hasClass("root")).toBeTruthy();
expect(
w
.children()
.first()
.hasClass("Bar")
).toBeTruthy();
我正在尝试检查子元素的 class:
import React from "react";
import { shallow, } from "enzyme";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
function Bar() {
return <div className="Bar" />;
}
function Component() {
return (
<div className="root">
<Bar />
</div>
);
}
describe("foo", () => {
it("should", () => {
const wrapper = shallow(<Component />);
console.log(wrapper.hasClass("root"));
console.log(
wrapper
.children()
.first()
.hasClass("Bar")
);
});
});
它打印 true
和 false
。为什么第二个 hasClass
returns false
?
这是一个demo
更新:
.html()
returns 所有元素这一事实具有误导性,我认为 shallow
实际上呈现了所有内容。
应该是
wrapper
.childAt(0)
.dive()
.hasClass("Bar")
如果您 mount
您的组件必须先渲染它才能工作:
const w = mount(<Component />).render();
expect(w.hasClass("root")).toBeTruthy();
expect(
w
.children()
.first()
.hasClass("Bar")
).toBeTruthy();