0

how can I test a decorated component? I decorated a component using the react-tracking library, like:

@track((props) => ({category: 'EDIT', page: 
props.history.location.pathname}))
class EditTemplate extends React.Component<Props, State> {...}

export default EditTemplate;

When I try to test it like this:

it("test description", () => {
    const wrapper = mount(<EditTemplate history={mockHistory}/>);
    expect(wrapper.prop("history")).toEqual("xyz");
    expect(wrapper.state("code")).toEqual("some value");
});

the prosp test works fine, but the state is always null! I tried using instance(), dive(), get(0), with the wrapper but the result it's always the same. If I remove the decorator, the test passes. Any suggestions? Thanks

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Peppe
  • 315
  • 5
  • 13
  • what does decorator do? – skyboyer Nov 07 '18 at 10:17
  • adds the track information to the component. It's the react-tracking library – Peppe Nov 07 '18 at 11:07
  • yes, missed that. so it's just ordinary HOC but used as decorator. don't see any magic there. have just played with example from docs and `wrapper.dive().state()` [definitely works](https://codesandbox.io/s/6w0v1717r?module=%2Fsrc%2Findex.spec.js&moduleview=1&previewwindow=tests) – skyboyer Nov 07 '18 at 12:52
  • it says that "state() can only be called on the root"... I created a function in the component that returns the state, and I got the state from that function directly and it works. I'd be nice to access to it without the workaround. – Peppe Nov 07 '18 at 15:54
  • so have you finally dealt with checking `props` and only `state` is left to work at? but do you really need accessing `state` directly? typically we call some callback prop or simulate some events and then just validate component's state through `.toMatchSnapshot()`. maybe it would be better to go this way. – skyboyer Nov 07 '18 at 16:09
  • also check https://stackoverflow.com/questions/44979735/how-does-one-access-state-on-a-nested-react-component-wrapped-by-an-hoc if it may help – skyboyer Nov 07 '18 at 16:10

0 Answers0