【问题标题】:How mock constructor variables in react js test cases file?react js测试用例文件中如何模拟构造函数变量?
【发布时间】:2020-12-10 09:34:58
【问题描述】:

我有一个名为 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”。

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

提前谢谢你。

【问题讨论】:

  • 你使用的是什么反应测试库?一般在获取组件实例时,可以给others属性赋值一个mocked值。
  • @slideshowp2 我正在使用 mocha 进行测试。你问的是这个吗?
  • @slideshowp2 谢谢,你的回答很有用,我可以模拟实例。

标签: reactjs unit-testing mocha.js


【解决方案1】:

感谢@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
    }
   ];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多