1
votes

I am writing a test for a component that is wrapped in a withStyles() from Material UI using Jest. I need to test the children elements, but my wrapper is undefined.

I've seen another post similar to writing tests with withStyles(), but the undefined error still persists.

Test File:

import { shallow } from 'enzyme';

import { TempComponent } from '../../../../src/components/helpers/temp';

describe('temp', () => {
  let wrapper;

  const renderComponent = () => shallow(<TempComponent />);

  beforeEach(() => {
    wrapper = renderComponent();
  });

  it('render correctly', () => {
    expect(wrapper.type()).toEqual('div');
  });
});

Component:

import React from 'react';
import { withStyles } from '@material-ui/core/styles';

const TempComponent = () => <button>Click Me!</button>;

export default withStyles({})(TempComponent);

I get this error for my test:

Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was undefined.

I am wanting the wrapper component to behave the same way as a wrapper without the withStyles() component. Any help would be appreciated!

Note: I am not doing snapchat testing with jest

1

1 Answers

0
votes

This appears to be the issue and solution:

https://github.com/mui-org/material-ui/issues/9266#issuecomment-349447137

The issue isn't about the children elements but with the intermediary element, it's creating. The shallow() API of enzyme only render one level depth. Any higher-order component is going to obfuscate the children. You have different workarounds. I would encourage you to refer to the enzyme documentation. Still, here they are: