How to jest mock the size
Are there any examples on how to mock the size for jest tests?
I'm using the sizeMe()(MyComponent) and expecting the size to come in as a prop. I've tried mocking the getBoundingClientRect but the size.width is still returning undefined.
add this modal to your mocks folder `import React from 'react';
const sizeMeProps = { size: { height: 770, position: null, width: 1200, }, };
const sizeMe = (options) => (Component) => { return (props) => <Component size={sizeMeProps.size} {...props} />; };
export const SizeMe = (props) => { return props.children(sizeMeProps); };
export default sizeMe;`
I'm using TypeScript and did the following.
My Props interface extended the SizeMeProps.
I exported with the withSize() HOC: export default withSize()(MyComponent).
Then I defined the size props in MyComponent.test.tsx.
const props = { size: { height: 25, width: 70, } };
Then simply spread them into my component when rendering in the test:
render(<MyComponent someRequredProps={blah} {...props} />);
We put react-sizeme.js in the src/__mocks__ directory
const sizeMeProps = {
size: {
height: 100,
width: 100,
},
};
export const withSize = () => (SizedComponent) => (props) => (
<SizedComponent size={sizeMeProps.size} {...props} />
);