使用 redux action creator 调用 onClick() 时应该测试什么?

Fun*_*zed 2 javascript reactjs jestjs enzyme

我正在尝试测试一个简单的复选框输入组件,该组件在其 onChange 方法中触发操作以保存复选框的值(真或假)。该组件如下:

import React, {Component} from 'react';
import uuid from 'uuid/v1';
import './styles.css';
import { connect } from 'react-redux';
import { saveCheckboxInput } from '../../actions/userInputActions';

class CheckboxSingle extends Component {

  constructor () {
    super();
    this.onChange = this.onChange.bind(this);
    this.state = {
      id : uuid(), // generate a unique id
    }
  }

  onChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    this.props.saveCheckboxInput(this.props.linkId, value, this.props.desc, this.props.relatedLinkIds, this.props.stepNumber);
  }

  render(){
    return(
      <div className="col-sm-12 no-padding-left">
        <label className="checkbox-container label-text">{this.props.desc}
          <input id={this.state.id} type="checkbox" name="checkBoxValue" checked={this.props.isChecked}
      onChange={(e) => this.onChange(e)}/>
          <span className="checkmark"></span>
        </label>
      </div>
    )
  }
}

function mapStateToProps(state, ownProps) {
  // Tie checkBoxValue to store answer
  // Get answers in the context of checkbox (determines if checked or not)
  var stepAnswers = state.userInputState.stepResponses[ownProps.stepNumber];
  var isCheckedValue = null;
  // Note: only functional w/ one checkbox input in flow
  // TODO: make functional for multiple checkbox inputs in flow
  for(var i=0; i < stepAnswers.length; i++) {
    if(stepAnswers[i].type === "questionnaire-checkbox-input") {
      isCheckedValue = stepAnswers[i].value;
    }
  }
  return {
    isChecked : isCheckedValue
  };
}



export default connect(
  mapStateToProps,
  { saveCheckboxInput },
 )(CheckboxSingle);
Run Code Online (Sandbox Code Playgroud)

通过测试模拟下面的 onChange() 函数:

describe('CheckboxSingle', () => {

  const initialState = {
    userInputState: {
       stepResponses: [
        {},
        {
          type: "questionnaire-checkbox-input",
          name: "mockLinkId",
          value: false,
          prefixText: "mockDesc",
          relatedLinkIds: ["mock1", "mock2"]
        }
      ]
    }
  }
  const mockStore = configureStore()
  let store, shallowWrapper, dispatch

  beforeEach(() => {
    store = mockStore(initialState)
    dispatch = jest.fn();
    shallowWrapper = shallow(<CheckboxSingle store={store} dispatch={dispatch} desc="mockDesc"
  linkId="mockLinkId" relatedLinkIds={["mock1", "mock2"]} stepNumber={1} />).dive()
  });    

  // TODO: test action creator firing upon click
  test('should call onChange after clicked', () => {
    const onChangeFake = jest.spyOn(shallowWrapper.instance(), 'onChange');
    shallowWrapper.find('input[type="checkbox"]').simulate('change', { target: { checked: true } });
    expect(onChangeFake).toHaveBeenCalledTimes(1);
  });

});
Run Code Online (Sandbox Code Playgroud)

测试 this.props.saveCheckboxInput 在组件更改时触发的最佳方法是什么(类似于模拟更改测试)?酶的新手,因此任何见解将不胜感激!

Oli*_*ssé 5

首先 onChange={(e) => this.onChange(e)}是一个不好的做法,因为它会为组件的每个渲染创建一个新函数,你可以简单地编写onChange={this.onChange}

然后要测试 propsaveCheckboxInput是否被调用,你只需要检查dispatch你的 store的函数是否已经被调用,并带有与原始saveCheckboxInput函数创建的动作相对应的参数

import { saveCheckboxInput } from '../../actions/userInputActions';

let store, shallowWrapper;

beforeEach(() => {
    store = mockStore(initialState)
    store.dispatch = jest.fn();
    shallowWrapper = shallow(
      <CheckboxSingle 
         store={store} 
         desc="mockDesc"
         linkId="mockLinkId" 
         relatedLinkIds={["mock1", "mock2"]} 
         stepNumber={1} 
      />
    ).dive();
}); 


test('should call onChange after clicked', () => {
  const action = saveCheckboxInput(
       "mockLinkId", 
       true, 
       "mockDesc", 
       ["mock1", "mock2"], 
       1
  );

  shallowWrapper.find('input[type="checkbox"]')
    .simulate('change', { target: { checked: true } });
  expect(store.dispatch).toHaveBeenCalledWith(action);
});
Run Code Online (Sandbox Code Playgroud)