首页 > 解决方案 > react js测试用例文件中如何模拟构造函数变量?

问题描述

我有一个名为 SelectedValues 的类,如下所示,它有一个全局变量“this.others”

export default class SelectedValues extends React.Component {

  /* istanbul ignore next */
  constructor(props) {
    super(props);
    this.renderOption = this.renderOption.bind(this);
    this.deselectOption = this.deselectOption.bind(this);
    this.others= [];
    this.state = {
      typedText: '',
      index: null,
      typedContext: '',
    };
  }
  
 deselectOption(event, option, index){
    const selectedOptions = _.clone(this.props.value);
    let selectedOptionsValue = _.split(selectedOptions.value, ';');

    selectedOptionsValue.splice(index, 1);
    console.log(this.others);
    let othersIndex =  this.others[index].OtherIndex;

    let typedUpdateContext = '';
    if(othersIndex === 0){
      let temp = this.others.find(item => item.OtherIndex === 1);
      typedUpdateContext = temp? temp.value : '';
    }

    _.remove(this.others, { 'key': option + index });
  }

  render(){
     return(...);
  }
}

代码工作正常,但是当我使用npm run test上述“deselectOption”方法运行测试文件时,我收到如下错误 TypeError: Cannot read property 'OtherIndex' of undefined

后来我发现问题是由于 this.others(这是一个全局变量)引起的,它是一个空数组。那么如何在测试文件中调用 deselectOption 方法之前模拟“this.others”。

我是为单元测试用例编写测试用例的新手。请帮我解决这个错误。

先感谢您。

标签: reactjsunit-testingmocha.js

解决方案


感谢@slideshowp2 提供建议,我可以在获取组件实例后模拟测试文件中的数据。

所以others是构造函数变量。为了模拟这个变量,我遵循了以下过程,它对我有用。

const wrapper = shallow(<SelectedValues value={input} onChange={onChangeSpy} />);
    const instance = wrapper.instance();
  //Below i am mocking "others" variable
   instance['others'] = [
    {
      'key':'Add 10 statements0',
      'value':'Add 10 statements',
      'OtherIndex': null
    },
    {
      'key':'Verify bank statements1',
      'value':'Verify bank statements',
      'OtherIndex': null
    },
    {
      'key':'Other2',
      'value':'loan',
      'OtherIndex': 1
    }
   ];

推荐阅读