Вот решение для модульного теста с использованием 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