【问题标题】:Testing for a 'null' component return value in React with Jest and Enzyme在 React 中使用 Jest 和 Enzyme 测试“null”组件返回值
【发布时间】:2018-09-15 11:30:03
【问题描述】:

正如标题所述,我正在尝试在反应组件上测试 null 返回值。

我已经尝试了解决方案here,但代码覆盖率表明我们没有正确测试第 7 行:return null。我在这里错过了什么?

组件:

import React from 'react';
import { func, bool } from 'prop-types';
import CloudyAlert from '../../assets/alert_cloud.svg';

const Alert = props => {
  if (!props.show) {
    return null;
  }
  return (
    <div onClick={props.onDismiss} className="alert">
      <img src={CloudyAlert} alt="alert to let you know time is up" />
      <button>Ok</button>
    </div>
  );
};

Alert.propTypes = {
  onDismiss: func.isRequired,
  show: bool
};

export default Alert;

测试:

import React from 'react';
import Enzyme from 'enzyme';
import Alert from '../Alert';
import { mount, shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

describe('Alert', () => {
  it('renders when show is true', () => {
    let wrapper = mount(<Alert onDismiss={jest.fn()} show />);

    it('renders correctly', () => {
      expect(toJson(wrapper)).toMatchSnapshot();
    });

    it('shows alert when start is clicked and time is zero', () => {
      expect(wrapper.find('Alert').props().show).toBe(true);
    });

    it('does not show alert when show is false', () => {
      wrapper = shallow(<Alert show={false} />);
      expect(wrapper.type()).toEqual(null);
    });
  });
});

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    已解决:相关测试嵌套在另一个“it”块中

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2018-08-20
      • 2017-04-13
      • 2021-06-24
      • 1970-01-01
      • 2017-11-26
      相关资源
      最近更新 更多