无法刺激子组件React Redux开玩笑中的更改事件

时间:2019-08-12 14:45:31

标签: reactjs redux jestjs enzyme

我是来应对redux的新手,并且正在尝试对FormContainer组件进行单元测试。但是我无法使用酶或玩笑来模拟Form组件上的更改事件。在wrapper.instance()中,我收到null,但我认为不应该这样。如果不是,那么测试FormContainer.js文件的正确方法是什么,因为当我运行测试范围时,它表明没有发现更改功能。

FormContainer.js

import React, { Component } from "react";
import { connect } from "react-redux";
import Form from "../components/Form";
import { isNumeric } from "../utils";

class FormContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      number: "",
      error: false
    };
  }
  // componentWillReceiveProps(nextProps) {
  //   console.log(nextProps, this.props, "main component");
  // }

  change = event => {
    let value = event.target.value;
    if (isNumeric(value) && value < 1001 && value >= 0) {
      if (value === "0") {
        this.setState({
          ...this.state,
          error: true
        });
        return;
      } else {
        this.setState({
          ...this.state,
          [event.target.name]: value,
          error: false
        });
      }
    } else {
      this.setState({ ...this.state, error: true });
    }
  };

  render() {
    return (
      <Form change={this.change} value={this.state} error={this.state.error} />
    );
  }
}
const mapStateToProps = state => {
  return { ...state };
};

export default connect(mapStateToProps)(FormContainer);

FormContainer.test.js

import React from 'react';
import configureStore from "redux-mock-store";
import { shallow,mount } from 'enzyme';
import FormContainer from '../../containers/FormContainer';
import { findByAttr } from '../../utils';
import Form from '../../components/Form';

describe("Testing Form container", () => {
    let wrapper;
    let store;
    beforeEach(() => {
        const initialState = {}
        const mockStore = configureStore();
        store = mockStore(initialState);
        wrapper = shallow(<FormContainer store={store} />);
    });
    it("Should render without error ", () => {
        expect(wrapper.exists()).toBe(true);
    });

    it("Simulate change", () => {
        let component = wrapper.find(Form);
        const mockChange = jest.fn();
        wrapper.instance().change = mockChange;
    });
});

测试表单容器›模拟更改

TypeError: Cannot set property 'change' of null

  22 |         let component = wrapper.find(Form);
  23 |         const mockChange = jest.fn();
> 24 |         wrapper.instance().change = mockChange;
     |         ^
  25 |     });
  26 | });

  at Object.<anonymous> (src/__test__/containers/FormContainer.test.js:24:9)

1 个答案:

答案 0 :(得分:0)

由于我们仅测试getAll()组件,因此不需要导入import Form from '../../components/Form';,因此将其删除。 并且没有名为FormContainer的事件侦听器,请改用change

onChange

尝试更改此规范:

<Form onChange={this.change} value={this.state} error={this.state.error} />

收件人:

it("Simulate change", () => {
    let component = wrapper.find(Form);
    const mockChange = jest.fn();
    wrapper.instance().change = mockChange;
});