试图像这样测试onChange
的功能,但将目标设为undefined
。
Login.js
handleInputChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
<Input
type="email"
name="email"
onChange={this.handleInputChange}
defaultValue={this.state.email}
/>
Login.test.js
it("test input onChange function", () => {
const wrapper = shallow(<Login store={store}/>).dive();
wrapper.find('Input').at(1).simulate('change', { target: { name: 'width', value: 50 } });
wrapper.update();
expect(wrapper.find("Input").at(1).props().value).toEqual(50);
});
答案 0 :(得分:0)
您最好使用Controlled Components而不是Uncontrolled Components。
对于受控组件,测试为:
login.jsx
:
import React, { Component } from 'react';
import { connect } from 'react-redux';
const Input = (props) => <input {...props} />;
class Login extends Component {
constructor() {
this.state = {
email: 0,
username: 0,
};
}
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
return (
<div>
<Input type="text" name="username" onChange={this.handleInputChange} value={this.state.username} />;
<Input type="email" name="email" onChange={this.handleInputChange} value={this.state.email} />;
</div>
);
}
}
export default connect()(Login);
login.test.jsx
:
import Login from './login';
import { shallow } from 'enzyme';
import configureMockStore from 'redux-mock-store';
const mockStore = configureMockStore();
describe('59799196', () => {
it('test input onChange function', () => {
const store = mockStore({});
const wrapper = shallow(<Login store={store} />).dive();
wrapper
.find('Input')
.at(1)
.simulate('change', { target: { name: 'email', value: 50 } });
wrapper.update();
expect(
wrapper
.find('Input')
.at(1)
.props().value,
).toEqual(50);
});
});
单元测试结果覆盖率100%:
PASS src/stackoverflow/59799196/login.test.jsx
59799196
✓ test input onChange function (19ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 92.86 | 100 | 80 | 100 | |
login.jsx | 92.86 | 100 | 80 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.857s, estimated 11s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59799196