【发布时间】: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