react-sticky icon indicating copy to clipboard operation
react-sticky copied to clipboard

How to test Sticky using enzyme / chai / mocha combo?

Open smolak opened this issue 8 years ago • 4 comments

Hi

I only had a very brief experience with Sticky and the only way of testing what Sticky renders is to do something like this:

// component
(...)
<Sticky>
{ () => { return (
    <div><Component1 some={prop} /><Component2 onClick={() => doSomething()} />
); } }
</Sticky>
(...)

-------------

// test

//not working
const component1 = parent.find(Component1);
//or
const component1 = parent.find(Sticky).find(Component1);

// working, but ugly
const sticky = parent.find(Sticky);
const stickysChildren = sticky.props().children().props.children;
const component1 = stickysChildren[0];
const component2 = stickysChildren[1];

Is there an elegant solution to testing Sticky? Updating parent component (via update() does not help).

smolak avatar May 26 '17 06:05 smolak

@smolak Yeah I'm having the same issue...

I wonder if this would be solved if the Sticky component was designed to accept a React Component or a function? Technically it's not a Higher Order Component (at least with respect to React) unless you can put a React component into it as a child, no?

keith-gould-zocdoc avatar May 26 '17 17:05 keith-gould-zocdoc

@dbarbalato Well at first i tried it just the standard way of plugging in a function as the child like you do in the guide. That works in practice, but doesn't work with enzyme / chai / mocha.

So after that I tried building a component that would effectively do the same thing. It would consume { style, isSticky } etc. off of the props it received, and would render the component accordingly. Unfortunately when I did this, the library complained because it's expected to receive a function, not an Object (If I'm correct React components are objects, despite also having a render function). I think the line in question causing that error would be this one:

https://github.com/captivationsoftware/react-sticky/blob/master/src/Sticky.js#L11

but the code in that file would probably need to be adjusted to also handle having a React component as a child rather than just a function.

EDIT: forgot to mention that when I used the React component, I extended off of Component, not PureComponent -- so it should be a full component, not just a functional one.

keith-gould-zocdoc avatar May 26 '17 18:05 keith-gould-zocdoc

I was able to get around this by just mocking Sticky using jest like so:

jest.mock('react-sticky', () => ({
    Sticky: (props) => props.children({ isSticky: false, style: {} }),
}));

keith-gould-zocdoc avatar May 26 '17 18:05 keith-gould-zocdoc

Hm @keith-gould-zocdoc so does this seem like a bug with how Sticky renders in Enzyme? I'm not super familiar with the quirks of rendering with Enzyme, but it does seem like it should call the child function.

vcarl avatar Mar 07 '18 14:03 vcarl