当我调整窗口大小并使用useLayoutEffect计算高度时,我正在尝试测试该功能组件中的功能组件。
该功能正常运行,但是我无法找到合适的文档来进行钩子测试。
所以我尝试过的是
app.test.js
import React from "react";
import { shallow } from "enzyme";
import App from "..";
describe("App Page", () => {
it("should render App Page", () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
it("should adjust the height on window resize", () => {
const wrapper = shallow(<App />);
global.innerHeight = 600;
global.dispatchEvent(new Event("resize"));
console.log(wrapper.debug()); // how can i test the useLayoutEffect
});
});
app.js
import React, { useLayoutEffect, useState, useEffect, useRef } from "react";
import { Layout } from "antd";
const { Header } = Layout;
function useWindowSize() {
const isClient = typeof window === "object";
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined,
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return false;
}
function handleResize() {
setWindowSize(getSize());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
const App = () => {
const headerRef = useRef(null);
const size = useWindowSize();
const [barHeight, setBarHeight] = useState(56);
useLayoutEffect(() => {
setBarHeight(headerRef.current.offsetHeight);
}, [size]);
return (
<Layout className="layout">
<HeaderContainer ref={headerRef}>
<Header>.....</Header>
</HeaderContainer>
</Layout>
);
};
export default App;
我应该使用get_browser还是有任何方法可以使用酶本身对其进行测试。
我们将不胜感激:)