我对酶很陌生。我正在测试两个组件。
form.jsx
const LoginForm = ({ style, handleSubmit }) => {
return (
<form onSubmit={handleSubmit}>
<Button type='submit'>
Login
</Button>
</form>
);
};
LoginForm.propTypes = {
handleSubmit: PropTypes.func.isRequired
};
我在另一个组件中使用此组件,如下所示:
Component.jsx
export default class Login extends Component {
constructor(props) {
super(props);
this.onLogin = this.onLogin.bind(this);
}
onLogin(event) {
event.preventDefault();
this.props.loginUser();
}
render() {
return (
<LoginForm style={loginFormStyles} handleSubmit={this.onLogin} />
);
}
}
Login.propTypes = {
auth: PropTypes.object.isRequired, //mapStateToProps
loginUser: PropTypes.func.isRequired //mapDispatchToProps
};
我已经为
form
编写了测试,并且通过了。form-test.js
it('should have a onSubmit handler', () => {
const props = {
handleSubmit: () => {}
};
const wrapper = shallow(<LoginForm {...props} />);
expect(_.isFunction(wrapper.props().onSubmit)).to.be.true;
});
it('should should call handlesubmit on form submission', () => {
const handleSubmit = sinon.spy();
const wrapper = shallow(<LoginForm handleSubmit={handleSubmit} />);
wrapper.simulate('submit');
expect(handleSubmit).to.have.been.called;
});
这些测试通过了。令人困惑的部分是:
1-如何从
onLogin
测试Component.jsx
中的form.jsx
功能?2-反之亦然,如果我必须从
onSubmit
触发form.jsx
的component.jsx
怎么办? 最佳答案
首先,您可以将Component.jsx
重命名为其他名称。
对于测试,您可以执行以下操作,
import Component from '../src/login';
import { stub } from 'sinon';
describe('login', () => {
it('should call onsubmit', () => {
const onSubmit = stub()
.withArgs('username', 'password');
const loginComponent = mount(<LoginForm handleSubmit={onSubmit} /> );
loginComponent.simulate('submit');
expect(onSubmit.calledOnce).to.equal(true);
});
});
我尚未对此进行测试,但它与您正在查看的内容很接近。
更新:
我测试了它,它正在工作。