反应测试在 wrapper.instance() 上失败

Val*_*lip 4 javascript reactjs jestjs enzyme

我是 React 单元测试的新手,我正在尝试为组件方法编写测试。

以下面的例子为例,我需要为 的changeHandler方法编写一个测试ComponentA

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

class ComponentA extends Component {
    changeHandler = () => {
        // additional logic here
    }

    render() {

        return (
            <div>
                <Field
                    name='text'
                    onChange={ () => this.changeHandler() }
                    component={renderTextField}>
                </Field>
            </div>
        );
    }
}

ComponentA.contextTypes = {
    router: PropTypes.object.isRequired
}

const mapStateToProps = (state)=> ({

})

const mapDispatchToProps = (dispatch) => ({

})

export default reduxForm({
    form: 'componentForm',
})(connect(mapStateToProps, mapDispatchToProps)(ComponentA));
Run Code Online (Sandbox Code Playgroud)

这就是我试图实现我的目标的方式:

import React from 'react';
import ComponentA from './ComponentA';
import { createMount } from '@material-ui/core/test-utils';
import Enzyme from 'enzyme';
import { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureMockStore from 'redux-mock-store';

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

describe('Component Form', () => {
  let mount, store, wrapper;

  const mockStore = configureMockStore({});
  beforeEach(() => {
    store = mockStore([]),
    mount = createMount({strict: false}),
    wrapper = shallow(<ComponentA store={store}/>).dive()
  });


  it('should change values', () => {
    wrapper.instance().changeHandler()
  });
});
Run Code Online (Sandbox Code Playgroud)

但是运行我得到的测试

类型错误:wrapper.instance(...).changeHandler 不是函数`

我不确定我做错了什么......我错过了什么吗?

额外细节:

使用shallow().dive().dive().dive().dive().dive().dive().dive()changeHandler方法出现,但我undefined在做时得到console.log(wrapper.instance().changeHandler()

  ComponentA {
        props: 
         { array: 
            { insert: [Function],
              move: [Function],
              pop: [Function],
              push: [Function],
              remove: [Function],
              removeAll: [Function],
              shift: [Function],
              splice: [Function],
              swap: [Function],
              unshift: [Function] },
           anyTouched: false,
           asyncValidate: [Function],
           asyncValidating: false,
           blur: [Function],
           change: [Function],
           clearSubmit: [Function],
           destroy: [Function],
           dirty: false,
           dispatch: [Function: dispatch],
           error: undefined,
           form: 'campaign',
           handleSubmit: [Function],
           initialize: [Function],
           initialized: false,
           initialValues: undefined,
           invalid: false,
           pristine: true,
           reset: [Function],
           resetSection: [Function],
           submitting: false,
           submitFailed: false,
           submitSucceeded: false,
           touch: [Function],
           untouch: [Function],
           valid: true,
           warning: undefined,
           currentUser: { username: 'test', userId: 1 },
           codes: { bitlyCompany: [] },
           config: { classificationsPermissions: [Object] },
           codeConfiguration: { status: 'In Progress' },
           store: 
            { getState: [Function: getState],
              getActions: [Function: getActions],
              dispatch: [Function: dispatch],
              clearActions: [Function: clearActions],
              subscribe: [Function: subscribe],
              replaceReducer: [Function: replaceReducer] },
           pure: true,
           validate: [Function],
           triggerSubmit: undefined,
           autofill: [Function],
           clearFields: [Function],
           clearSubmitErrors: [Function],
           clearAsyncError: [Function],
           submit: [Function],
           storeSubscription: 
            Subscription {
              store: [Object],
              parentSub: [Object],
              onStateChange: [Function: bound onStateChange],
              unsubscribe: [Function: unsubscribe],
              listeners: [Object] },
           },
        context: { router: undefined },
        refs: {},
        updater: 
         Updater {
           _renderer: 
            ReactShallowRenderer {
              _context: [Object],
              _element: [Object],
              _instance: [Circular],
              _newState: null,
              _rendered: [Object],
              _rendering: false,
              _forcedUpdate: false,
              _updater: [Circular],
              _dispatcher: [Object],
              _workInProgressHook: null,
              _firstWorkInProgressHook: null,
              _isReRender: false,
              _didScheduleRenderPhaseUpdate: false,
              _renderPhaseUpdates: null,
              _numberOfReRenders: 0 },
           _callbacks: [] },
        changeHandler: [Function],
        setState: [Function], }
Run Code Online (Sandbox Code Playgroud)

eta*_*han 5

如果你能知道console.log结果会有所帮助,wrapper.instance()这样我们就可以看到实际返回的内容。

我的猜测是您的组件被包裹在多个 HOC 中,这就是为什么您应该深入了解,直到找到带有changeHandler.

这意味着它看起来像这样:

wrapper = shallow(<ComponentA store={store}/>).dive().dive() // etc.
Run Code Online (Sandbox Code Playgroud)

或者,您可以在现场模拟更改事件并使用它来测试您的处理程序。它看起来像下面这样:

wrapper.find(Field).simulate('change')
Run Code Online (Sandbox Code Playgroud)