I am trying to test a functional component in that functional component when I do the resize of the window I am calculating the height using useLayoutEffect.
The feature is working, but I was not able to find a proper doc for testing with hooks.
So what I have tried is
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;
Should I use https://www.npmjs.com/package/@testing-library/react-hooks for these or is there any way to test it using Enzyme itself.