测试方法 else/if 未返回预期值
Test Method else/if not returning expected value
正在尝试测试下面的方法。测试目前仅返回 'column'。只是想知道如何测试其他人,例如 'polar'、'columnstacked' 等。
getChartType = () => {
if (this.props.defaultData.stacked === 'polar') {
return 'polar'
}
else {
if(this.props.defaultData.stacked === 'false'){
return this.props.defaultData.type
}
else{
if(this.props.defaultData.stacked === 'true' && this.props.defaultData.type === 'column'){
return 'columnstacked'
}
else if(this.props.defaultData.stacked === 'true' && this.props.defaultData.type === 'bar'){
return 'barstacked'
}
}
return 'column'
为 React Js 使用 Jest 和 Enzyme。
浅渲染我的组件
这是我目前的测试结果。
it('Test getChartType method',() => {
wrapper.setProps({
defaultData:{
stacked:"",
type:"",
category:{
$:{
id:{},
},
},
}})
wrapper.update();
expect(wrapper.instance().getChartType({defaultData:{stacked:""}})).toEqual("column"); //WORKING
expect(wrapper.instance().getChartType({defaultData:{stacked:"percent", type:'area'}})).toEqual("areastacked100"); //NOT WORKING
});
我认为这里的问题是 getChartType
函数。
在测试中,代码将对象作为参数发送({defaultData:{stacked:""}}
),但函数getChartType
不接受任何参数;它读取它的 props
.
这就是为什么很难测试;在隔离测试中,props
总是相同的。我建议将 getChartType
转换为接受对象参数的函数。在您的代码中,您将发送 props
或 props
的一部分;在你的测试中,你将发送你的对象。
该函数将更易于测试和理解,因为您不依赖于函数外部的某些东西 (props
)。
正在尝试测试下面的方法。测试目前仅返回 'column'。只是想知道如何测试其他人,例如 'polar'、'columnstacked' 等。
getChartType = () => {
if (this.props.defaultData.stacked === 'polar') {
return 'polar'
}
else {
if(this.props.defaultData.stacked === 'false'){
return this.props.defaultData.type
}
else{
if(this.props.defaultData.stacked === 'true' && this.props.defaultData.type === 'column'){
return 'columnstacked'
}
else if(this.props.defaultData.stacked === 'true' && this.props.defaultData.type === 'bar'){
return 'barstacked'
}
}
return 'column'
为 React Js 使用 Jest 和 Enzyme。 浅渲染我的组件 这是我目前的测试结果。
it('Test getChartType method',() => {
wrapper.setProps({
defaultData:{
stacked:"",
type:"",
category:{
$:{
id:{},
},
},
}})
wrapper.update();
expect(wrapper.instance().getChartType({defaultData:{stacked:""}})).toEqual("column"); //WORKING
expect(wrapper.instance().getChartType({defaultData:{stacked:"percent", type:'area'}})).toEqual("areastacked100"); //NOT WORKING
});
我认为这里的问题是 getChartType
函数。
在测试中,代码将对象作为参数发送({defaultData:{stacked:""}}
),但函数getChartType
不接受任何参数;它读取它的 props
.
这就是为什么很难测试;在隔离测试中,props
总是相同的。我建议将 getChartType
转换为接受对象参数的函数。在您的代码中,您将发送 props
或 props
的一部分;在你的测试中,你将发送你的对象。
该函数将更易于测试和理解,因为您不依赖于函数外部的某些东西 (props
)。