jest+enzyme对react组件进行单元测试

shallow浅渲染、render深渲染、mount测试交互

    <div className={style.buttonWrap}>
      <Tooltip title={tipsText} placement="top" {...tipsSetting}>
        <Button
          disabled={disabled}
          onClick={() => {
            handleClick(id);
          }}
          id={id}
        >
          {icon}
          {text}
        </Button>
      </Tooltip>
    </div>

1.组件中有两个子组件组成,首先设置两个测试用例,一个测试按钮提示是否存在,一个测试按钮是否存在,浅渲染因不会渲染子组件,所以这两个用例使用shallow即可
注意find的时候选择器应当是大驼峰的组件名称,而不是html标签名称button

it('should has Tooltip', () => {
  const { wrapper } = setup();
  expect(wrapper.find('Tooltip').length).toBe(1);
});

it('should has Button', () => {
  const { wrapper } = setup();
  expect(wrapper.find('Button').length).toBe(1);
});

2.测试按钮文字内容是否正确
经审查元素,发现文字在多个标签里面,且在大的Button组件内部,所以需要使用深渲染render,且选择器为标签选择器,而不为组件名。

it('should render button', () => {
  const { wrapper } = setupByRender();
  expect(wrapper.find('button').text()).toBe(props.text);
});

it('should render button icon', () => {
  const { wrapper } = setupByRender();
  expect(wrapper.find('button i').hasClass(props.iconName)).toBe(true);
});

3.mount测试交互
对该按钮的交互测试需要模拟点击事件,使用simulate方法,点击断言某个方法是否被调用,注意:模拟点击的是按钮组件,不是标签。

it('click item to be done', () => {
  const { wrapper } = setupByMount();
  wrapper
    .find('Button')
    .at(0)
    .simulate('click');
  expect(props.handleClick).toBeCalled();
});

关于enzyme的API exists,需要在mount中使用,否则报错其不是一个方法。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容