P
P
Pavel Didenko2019-12-09 10:17:27
React
Pavel Didenko, 2019-12-09 10:17:27

How to test components wrapped with withStyles material-ui?

I am developing an application with the material-ui framework. Started writing tests and ran into a problem when writing tests for a component wrapped in the withStyles HOC.
This error pops up:

TypeError: Cannot read property 'main' of undefined

And here is the location of this error:
label: {
  fontSize: 12, 
  color: palette.gray.main
}

The function that returns the styles object is passed as a parameter the application theme from which the palette gets, which the HOC specified in the description above forwards there, but during testing it apparently cannot reach the theme and gets undefined. Either the import of the styles function is first read before reaching the HOC, and it will logically be undefined in it.
Who faced such a thing, how did you solve the problem?
PS destructuring to each object to get at least undefined as a value - a crutch that you really don't want to do. Plus nested components can be wrapped too

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Didenko, 2019-12-09
@Dasslier

I found such a solution, which of the experts, correct if something is wrong and then how to do it more correctly:
I import from the 'react-test-renderer' package:
From a component, I import a component that is not wrapped in HOC with a regular export. And now there is no deep rendering for the snapshot:

it('Profile renders snapshot', () => {
        const renderer = new ShallowRenderer();
        const result = renderer.render(<Profile />);
        expect(result).toMatchSnapshot();
    });

Another option for dealing with MobX and decorators:
If the component is wrapped in an inject, the above method will take a useless snapshot. To take a normal snapshot of a component, do this:
it('ProfileMainInfo renders snapshot', () => {
        const renderer = new ShallowRenderer();
        const result = renderer.render(<ProfileMainInfo.wrappedComponent {...props} />);
        expect(result).toMatchSnapshot();
    });

That is, we turn to the wrappedComponent property, it contains the wrapped component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question