I have this function in which I have the following conditions. How can I test it? In other cases it is testing only the first condition and then else
is not being tested.
handleChange = async (select) => {
const { data1, data2 } = this.state;
if (data1.value === 'a') {
await this.setState({
data2: {
...data2,
userId: selection.value
}
});
}
if (data1.value === 'b') {
await this.setState({
data2: {
...data2,
list: select
},
employees: select
});
}
};
Here is the unit test solution:
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'],
});
});
});
unit test results with 100% coverage:
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
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61390419
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.