使用材质UI withStyles组件进行浅层渲染笑话测试

时间:2019-05-16 17:27:08

标签: reactjs jestjs material-ui

我正在编写一个测试,用于使用Jest从Material UI中包装在withStyles()中的组件。我需要测试子元素,但是我的包装器未定义。

我看过另一篇与用withStyles()编写测试类似的文章,但是未定义的错误仍然存​​在。

测试文件:

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

组件:

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

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

export default withStyles({})(TempComponent);

测试时出现此错误:

不变违反:ReactShallowRenderer render():浅渲染仅适用于自定义组件,但是提供的元素类型为undefined

我希望包装器组件的行为与没有withStyles()组件的包装器相同。任何帮助将不胜感激!

注意:我不是在开玩笑地进行

1 个答案:

答案 0 :(得分:0)

这似乎是问题所在和解决方案:

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

  

问题不在于子元素,而是中介   元素,它正在创造。酶的shallow() API仅能渲染一个   水平深度。任何更高阶的成分都会混淆   孩子们。您有不同的解决方法。我鼓励你   请参阅酶文档。不过,它们在这里:

     
      
  • 使用mount()
  •   
  • 使用.dive()
  •   
  • 使用我们的createShallow() public API
  •   
  • 使用我们的内部until()帮助程序
  •   
相关问题