酶单位测试,如何在不导出子成分的情况下测试成分?

时间:2020-03-03 23:10:40

标签: reactjs enzyme

https://enzymejs.github.io/enzyme/docs/api/mount.html https://medium.com/@samuelhutama/unit-testing-react-component-with-jest-and-enzyme-without-snapshot-test-5b26b8146abf

请参阅我的主要代码,我不想导出子组件。

import React from 'react';
import PropTypes from 'prop-types';

// eslint-disable-next-line react/prop-types
const DemoMessageBody = ({ inner }) => (
  // eslint-disable-next-line react/no-danger
  <div dangerouslySetInnerHTML={{ __html: inner }} />
);

const DemoMessage = ({
  // eslint-disable-next-line react/prop-types
  msgTitle, msgBody,
}) => (
  <div>
    <p>
      <strong>{msgTitle}</strong>
    </p>
    <DemoMessageBody inner={msgBody} />
  </div>
);

/**
 * Dispatch to the corresponding alert message box based on message type
 * @param {Object} alert message details including title, type and message body
 */
const Demo = ({ msgTitle, msgBody }) => {
  return DemoMessage({ msgTitle, msgBody });
};

Demo.propTypes = {
  /**
   * Message box title
   */
  msgTitle: PropTypes.string,
  /**
   * Message type, this can be a html element or plain string
   */
  msgBody: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element,
  ]),
};

Demo.defaultProps = {
  msgTitle: 'Sth is wrong',
  msgBody: 'Please contact your admin',
};

export default Demo;

测试就是这样

import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Demo from '../Demo';

describe('DisplayMessageFromHtmlElement', () => {
  let prefix;
  let postfix;
  let testTitle;

  beforeEach(() => {
    prefix = 'Your request cannot be processed';
    postfix = 'Contact the admin.';
    testTitle = 'Test Title';
  });

  test('should show info message', () => {
    const msg1 = 'Info msg 1';
    const msg2 = 'Info msg 2';
    const inputMsg = (
      <div>
        <p>{prefix}</p>
        <ol>
          <li>{msg1}</li>
          <li>{msg2}</li>
        </ol>
        <p>{postfix}</p>
      </div>
    );

    const wrapper = mount(<Demo msgTitle={testTitle} msgBody={inputMsg} />);
    expect(wrapper).toMatchSnapshot();
  });
});

现在,当我运行测试时,快照不会花费在解析最终的html上(在手动测试中有效),它仍然显示“ DemoMessageBody”,“ dangerouslySetInnerHTML”。

我的猜测是,如果我将子组件导出到它们自己的文件中,则可以使用。但是我不想导出它们。

有什么建议吗?

0 个答案:

没有答案
相关问题