开玩笑模拟material-ui组件以检查其渲染

时间:2018-12-12 00:48:02

标签: reactjs jestjs enzyme

我想用Jest测试以下代码。我只是尝试模拟MenuItem组件以查看它已被调用多少次,但是我收到了一个错误。

我还遇到了this问题,但是Material-ui呈现了具有奇怪名称的组件。

然后我以here结尾,但没有一个对我有用的预先回答的问题。

{
   menuItems.map(menuItem => (
    <MenuItem key={menuItem.value} value={menuItem.value}>
       {menuItem.description}
    </MenuItem>
   ))
}

test.js

import React from 'react';
import MenuItem from '@material-ui/core/MenuItem';
import { SimpleSelect } from './SimpleSelect';
import { shallowWithTheme, mountWithTheme } from '../helper';

describe('SimpleSelect component', () => {
  jest.mock('@material-ui/core/MenuItem', () => jest.fn(() => {}));
  let callback;
  beforeEach(() => {
    callback = jest.fn();
  });

  it('should render menu item', () => {
    const menuItems = [
      {
        value: '12',
        description: 'Description 123',
      },
      {
        value: '456',
        description: 'Description 456',
      },
    ];
    mountWithTheme(<SimpleSelect className="test" label="test" selected="default" onChange={callback} menuItems={menuItems} />);
    expect(MenuItem).toHaveBeenCalled();
  });
});

错误 enter image description here

已编辑

expect(wrapper.find(MenuItem)).toHaveLength(2); 
expect(wrapper.find(MenuItem).length).toHaveLength(2);
expect(wrapper.find(MenuItem).length).toBe(2);

错误

enter image description here

其他尝试出错 enter image description here

已编辑:19年12月14日

export const shallowWithTheme = children => (
  shallow(children, { theme })
);

export const mountWithTheme = (children, options) => (
  mount(<ThemeProvider theme={theme}>{children}</ThemeProvider>, options)
);

样式组件版本4

"styled-components": "^4.1.1"

wrapper.debug()输出

与shallowWrapper

enter image description here

使用mountWrapper enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

此外,您不能以这种方式模拟构造函数,而根本不需要模拟它。

使用shallow()代替mount + find,可以检查MenuItem的计数。另外,请检查.mockClear()的工作方式-您无需重新创建模拟的回调。

describe('SimpleSelect component', () => {
  let callback = jest.fn();
  beforeEach(() => {
    callback.mockClear();
  });

  it('should render menu item', () => {
    const menuItems = [
      {
        value: '12',
        description: 'Description 123',
      },
      {
        value: '456',
        description: 'Description 456',
      },
    ];
    const wrapper = shallowWithTheme(<SimpleSelect className="test" label="test" selected="default" onChange={callback} menuItems={menuItems} />);
    expect(wrapper.find(MenuItem)).toHaveLength(12);
  });
});