我有以下代码:
render(){
const nullValue = (
<span>
-
</span>
)
const value = (propValue) => { //untested line
if (propValue === null) { //untested line
return nullValue //untested line
} else {
return ( //untested line
<span>
{propValue}
</span>
)
}
}
const percentageValue = (percentagePropValue) => { //untested line
if (percentagePropValue === null) { //untested line
return nullValue //untested line
} else {
return ( //untested line
<span>
{percentagePropValue * 100}%
</span>
)
}
}
return ( //untested line
<div>
<h1>Object Name: {value(this.state.myObject.name)}</h1>
<h2>Object Percentage: {percentageValue(this.state.myObject.percentage)}</h2>
</div>
)
}
上面的想法是value
和percentageValue
函数使用对象属性作为参数,然后将值返回给用户。如果property的值恰好是null
,则将其替换为破折号。
在组件上运行测试覆盖率时,它表示未测试value
和percentageValue
函数。我假设这是因为if / else条件。在这种情况下我该怎么办?我真的不知道该如何处理。
答案 0 :(得分:2)
这是使用enzyme
的单元测试解决方案:
index.jsx
:
import React, { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
myObject: {
name: null,
percentage: null,
},
};
}
render() {
const nullValue = <span>-</span>;
const value = (propValue) => {
if (propValue === null) {
return nullValue;
} else {
return <span>{propValue}</span>;
}
};
const percentageValue = (percentagePropValue) => {
if (percentagePropValue === null) {
return nullValue;
} else {
return <span>{percentagePropValue * 100}%</span>;
}
};
return (
<div>
<h1>Object Name: {value(this.state.myObject.name)}</h1>
<h2>Object Percentage: {percentageValue(this.state.myObject.percentage)}</h2>
</div>
);
}
}
index.test.jsx
:
import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';
describe('61622176', () => {
it('should render null object name and null object percentage', () => {
const wrapper = shallow(<MyComponent></MyComponent>);
expect(
wrapper.find('h1').contains([
<h1>
Object Name: <span>-</span>
</h1>,
<h2>
Object Percentage: <span>-</span>
</h2>,
]),
);
});
it('should render object name and object percentage', () => {
const wrapper = shallow(<MyComponent></MyComponent>);
wrapper.setState({ myObject: { name: 'ok', percentage: 0.5 } });
expect(
wrapper.find('h1').contains([
<h1>
Object Name: <span>ok</span>
</h1>,
<h2>
Object Percentage: <span>50%</span>
</h2>,
]),
);
});
});
具有100%覆盖率的单元测试结果:
PASS stackoverflow/61622176/index.test.jsx (8.017s)
61622176
✓ should render null object name and null object percentage (9ms)
✓ should render object name and object percentage (1ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.jsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.039s