Codesanbox链接-包括工作组件 Child2.js 和工作测试 Child2.test.js
Child2.js
import React, { useRef } from "react";
export default function Child2() {
const divRef = useRef();
function getDivWidth() {
if (divRef.current) {
console.log(divRef.current);
}
return divRef.current ? divRef.current.offsetWidth : "";
}
function getDivText() {
const divWidth = getDivWidth();
if (divWidth) {
if (divWidth > 100) {
return "ABC";
}
return "123";
}
return "123";
}
return (
<>
<div id="myDiv" ref={divRef}>
{getDivText()}
</div>
<p>Div width is: {getDivWidth()}</p>
</>
);
}
Child2.test.js
import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import Child2 from "../src/Child2";
Enzyme.configure({ adapter: new Adapter() });
it("div text is ABC when div width is more then 100 ", () => {
const wrapper = shallow(<Child2 />);
expect(wrapper.find("#myDiv").exists()).toBe(true);
expect(wrapper.find("#myDiv").text()).toBe("ABC");
});
it("div text is 123 when div width is less then 100 ", () => {
const wrapper = shallow(<Child2 />);
expect(wrapper.find("#myDiv").exists()).toBe(true);
expect(wrapper.find("#myDiv").text()).toBe("123");
});
当我运行测试时,显然 div 的 offsetWidth 为 0,因此我需要找到一种方法来模拟useRef
返回具有宽度的 div 元素或模拟getDivWidth
函数以返回所需的宽度数字。
我怎么能做到这一点?我已经寻找了解决方案,但我被卡住了。有一些带有类组件或使用typescript的示例,但我没有设法使用。