Вот решение для модульного теста:
index.jsx
:
import React, { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data1: { value: 'a' },
data2: { userId: 1, list: [] },
employees: [],
};
}
handleChange = async (select) => {
const { data1, data2 } = this.state;
if (data1.value === 'a') {
this.setState({
data2: {
...data2,
userId: select.value,
},
});
}
if (data1.value === 'b') {
this.setState({
data2: {
...data2,
list: select,
},
employees: select,
});
}
};
render() {
return <div>my component</div>;
}
}
index.test.jsx
:
import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';
describe('61390419', () => {
it('should handle change if data1.value === "a"', () => {
const wrapper = shallow(<MyComponent></MyComponent>);
const select = { value: 2 };
wrapper.instance().handleChange(select);
expect(wrapper.state().data2).toEqual({ userId: 2, list: [] });
});
it('should handle change if data1.value === "b"', () => {
const wrapper = shallow(<MyComponent></MyComponent>);
wrapper.setState({ data1: { value: 'b' } });
const select = ['1', '2'];
wrapper.instance().handleChange(select);
expect(wrapper.state()).toEqual({
data1: { value: 'b' },
data2: { userId: 1, list: ['1', '2'] },
employees: ['1', '2'],
});
});
});
Результаты модульного теста со 100% покрытием:
PASS stackoverflow/61390419/index.test.jsx (12.259s)
61390419
✓ should handle change if data1.value === "a" (12ms)
✓ should handle change if data1.value === "b" (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: 14.371s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61390419