间谍在componentDidMount

时间:2018-05-15 11:34:05

标签: reactjs unit-testing testing jestjs enzyme

我最近想测试一些自定义方法是否在React组件的componentDidMount方法中调用。

componentDidMount() {
        this.props.actions.getDocuments();
    }

我正在使用Jest作为我的测试框架,其中包括针对模拟/间谍的jest.fn()

    function setup(data) {
        const props = {
            session: {},
            actions: {
                getDocuments: jest.fn()
            }
        };
        const wrapper = mount(<ComponentList {...props} />,
            {
                context: { muiTheme: getMuiTheme() },
                childContextTypes: { muiTheme: React.PropTypes.object.isRequired }
            }
        );

        return {
            props,
            wrapper
        };
    }

describe('compenent:', () => {
    let component;
    describe('Given that the container is loaded', () => {
         beforeAll(() => {
             component = setup();
         });
        it('should call the getDocuments to get the data', () => {
            expect(component.props.actions.getDocuments).toHaveBeenCalled();
        });
    });
    });

此代码失败并引发以下错误:

TypeError: received.getMockName is not a function

      at Object.<anonymous> (src/containers/ComponentList/ComponentList.spec.js:61:158)
          at new Promise (<anonymous>)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

如果我使用sinon而不是jest,我仍然会收到错误:

expect(jest.fn())[.not].toHaveBeenCalled()

    jest.fn() value must be a mock function or spy.
    Received:
      function: [Function proxy]

      at Object.<anonymous> (src/containers/ComponentList/ComponentList.spec.js:61:158)
          at new Promise (<anonymous>)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

是否可以使用Jest或Sinon测试此功能?如果是这样,怎么样?

这是我的代码实现:

export class ComponentList extends React.Component {
    constructor(props) {
        super(props)
    }
    componentDidMount() {
        this.props.actions.getDocuments();
    }
    render() {
        return (
            <div className="allowScroll">
                ....
            </div>
        )
    }
}

ComponentList.propTypes = {
    document: PropTypes.object,
    actions: PropTypes.object.isRequired
};

const mapStateToProps = (state) => {
    return {
        document: state.document
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(componentActions, dispatch)
    };
}
export default connect(mapStateToProps, mapDispatchToProps)(ComponentList)

2 个答案:

答案 0 :(得分:0)

尝试component.wrapper.props().actions.getDocuments

而不是component.props.actions.getDocuments

希望这有帮助。

答案 1 :(得分:0)

浅层渲染将验证此测试 def medical_plan_upload(self): medicalplanread = ReadExcel() getmodeldata = GetModelData() # read plans excel df = medicalplanread.readplanexcel() MedicalPlan_dict = [] try: headers = getmodeldata.get_medical_plans_headers() dataframe = df[df.columns.intersection(headers)] commonColumns = dataframe.columns.tolist() # iterate through the dataframe - get value for issuer table and insert/update in medical plan table for index, frame in df.iterrows(): temp_dict = {} # reading from Issuer table issuerid = getmodeldata.get_issuer(frame['wellthie_issuer_identifier']) # reading from Service_area table service_area_id = getmodeldata.get_serviceArea(frame['service_area_identifier']) if service_area_id is not None and issuerid is not None: # reading from medical plans table medical_plan = getmodeldata.get_medicalplans(issuerid, frame['hios_plan_identifier'], frame['plan_year'], frame['group_or_individual_plan_type']) if not medical_plan: # check if medical_plan is [] medical_plans_data = frame.to_dict() for key, value in medical_plans_data.iteritems(): if key in commonColumns: if pd.isna(value): value = None temp_dict[key] = value else: temp_dict[key] = value temp_dict["issuer_id"] = issuerid temp_dict["service_area_id"] = service_area_id MedicalPlan_dict.append(temp_dict) # new_plan = MedicalPlan(**temp_dict) # sess.add(new_plan) # sess.commit() else: print ("row number..", index, " is already in the db...") continue else: print ("row number.. ", index, "is invalid") engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/test_biz_dev') conn = engine.connect() conn.execute(MedicalPlan.__table__.insert(), MedicalPlan_dict) except Exception as e: print e finally: conn.close() ,并返回true。用浅层替换安装。