无状态组件返回“ null”以进行浅层快照测试

时间:2019-03-25 09:22:03

标签: reactjs jestjs enzyme

我有一个无状态组件。

我正在为单元测试匹配快照。

但是它返回null

规范

import React from 'react';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import StatelessComponent from 'components/elements/StatelessComponent';


describe('<StatelessComponent />', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<StatelessComponent />);
  });

  it ('should render with default props', () => {
    expect(shallowToJson(wrapper)).toMatchSnapshot();
  });
});

组件

export const StatelessComponent = () => (
  <div className={styles['container']}>
    <div className={styles['description']}>
      <FormattedMessage {...emailErrorInfo} />
    </div>
  </div>
);

快照

exports[`<StatelessComponent /> should render with default props 1`] = `null`;

2 个答案:

答案 0 :(得分:2)

这样导入StatelessComponent,因为它不是默认导出

import { StatelessComponent } from 'components/elements/StatelessComponent';

答案 1 :(得分:1)

将无状态组件默认导出即可解决此问题。

const StatelessComponent = () => (
  <div className={styles['container']}>
    <div className={styles['description']}>
      <FormattedMessage {...emailErrorInfo} />
    </div>
  </div>
);

export default StatelessComponent