reactjs - 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”。
我是为单元测试用例编写测试用例的新手。请帮我解决这个错误。
先感谢您。
解决方案
感谢@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
}
];
推荐阅读
- python - 是否有在 Google Colab 上运行 Web 应用程序的通用方法?
- python - Python(正则表达式:替换单个字母后的每个字符)
- elf - 需要将 OMF 文件转换为 ELF 文件格式
- facebook - FB信使。是否有任何解决方案可以解决并非所有用户消息都被传递(FB 端的错误 403)?
- reactjs - ReactJS - 更新状态数组导致不同组件中的未定义
- r - 用户自定义函数,用于从 excel 和 SQL 读取和操作常用数据
- python - 使用 dpkt 和 python 分析 pcap 文件
- javascript - Firebase 存储规则 经过身份验证的用户的私有 URL(没有 downloadURL 或库)
- angular - Angular 自定义验证器在其中使用订阅时不会引发错误
- mysql - 如何使这个 SQL 查询与 mysql 8 一起工作