I am testing a react hook which gets the window-dimensions from window.innerheight and window.innerwidth. It uses the following code to handle server side rendering:
...
typeof window=="undefined" ? {width: 1024, height: 768} : functionToGetDimensions()
...
When trying to make tests for this line in react-testing-library i need to delete the window object:
...
const TestComponent = ({ }) => {
const { width, height } = useWindowDimensions();
return (
<div>
<p data-testid="width">{width}</p>
<p data-testid="height">{height}</p>
</div>)
}
describe('when window is undefined', () => {
//@ts-ignore
const testWidth = 1000;
const testHeight = 800;
const fallbackWidth = 1024; // when useWindowdimensions detects window = undefined
const { window } = global;
beforeAll(() => {
// @ts-ignore
delete global.window;
});
afterAll(() => {
global.window = window;
});
it('runs without error', () => {
render(<TestComponent />)
expect(screen.queryByTestId("height")).toHaveTextContent(fallbackWidth );
});
});
I get the following error:
ReferenceError: window is not defined
I've tried using node as test enviroment, but then document is not defined, and render does not work.
Aucun commentaire:
Enregistrer un commentaire