ctrlplusb / react-sizeme

Make your React Components aware of their width and height!
MIT License
1.95k stars 94 forks source link

How to jest mock the size #193

Open miyagiborn opened 4 years ago

miyagiborn commented 4 years ago

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.

ilanrot90 commented 4 years ago

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;`

TomPlum commented 3 years ago

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} />);

william10000 commented 3 years ago

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} />
);