【问题标题】:Unit Testing AntD Modal with Jest and Enzyme使用 Jest 和 Enzyme 对 AntD 模态进行单元测试
【发布时间】:2019-07-28 01:17:03
【问题描述】:

我正在尝试使用 Jest 和 Enezym 在 React 中对 AntD 模态进行单元测试,它给了我以下错误:

还有一个

这也是: Invariant Violation:对象作为 React 子对象无效(发现:带有键 {destroy, update} 的对象)。如果您打算渲染一组子项,请改用数组。

这是我创建的模态

import propTypes from 'prop-types';
import { Modal } from 'antd';

const SuccessModal = props => {
const { title, content } = props;
return Modal.success({
title,
content,
});
   };

SuccessModal.propTypes = {
title: propTypes.string.isRequired,
content: propTypes.string.isRequired,
  };
  export default SuccessModal;

这是我的单元测试

import React from 'react';
import { shallow } from 'enzyme';
import SuccessModal from './index';

describe('SuccessModal', () => {
  it('should render the component correctly in ', () => {
    shallow(<SuccessModal title="time to succeed" content="sucess content        success content" />);
  });
  it('check the props values', () => {
    const props = {
      title: 'this is a success title',
      content: 'sucess content sucess content',
    };

    const renderedComponent = shallow(<SuccessModal {...props} />);
    expect(renderedComponent.prop('title')).toBe('this is a success title');
    expect(renderedComponent.prop('content')).toBe('sucess content sucess content');
  });
});

我也试过这种方式

  expect(

        (      
    <SuccessModal title="this is a success title" content="sucess content sucess content" />
  ).exists(),
).toEqual(true);
expect((   <SuccessModal title="this is a success title" content="sucess content sucess content" />).text()).toContain('this is a success title');

非常感谢任何帮助,如果需要更多说明,请在评论中告诉我

【问题讨论】:

  • 你找到解决办法了吗?

标签: reactjs jestjs enzyme antd


【解决方案1】:

由于这个问题是在差不多 2 年前被问到的,那么我认为使用的是 antd 3.x

Modal.success 返回一个对象 {destroy, update} 因此相应的错误: “不变违规:对象作为 React 子项无效(发现:带有键 {destroy, update} 的对象)...”

这里你需要使用声明式方法:

const SuccessModal = props => {
    const {title, content} = props;
    return (
        <Modal title={title}> 
            {content}
        </Modal>
    );
};

然后测试你想要的方式。

或者像函数一样调用 SuccessModal。

SuccessModal(props);

当作为函数调用时,modal 会在body 标记内创建为单独的div。因此,要检查调用的正确性,必须检查 DOM

expect(document.documentElement.outerHTML).toContain(props.title);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 2019-10-26
    • 2019-12-08
    • 1970-01-01
    • 2018-12-16
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多