【发布时间】:2015-08-28 22:46:17
【问题描述】:
所以我有一个看起来像这样的反应组件:
class SignInForm extends React.Component {
constructor(props) {
super(props);
}
onFormSubmit(event) {
const username = React.findDOMNode(this.refs.username).value;
const password = React.findDOMNode(this.refs.username).value;
// very basic validation
if (username && password.length > 6) {
this.props.flux.signIn({ username, password });
}
event.preventDefault();
}
render() {
return (
<form onSubmit={ this.onFormSubmit.bind(this) } >
<input type="text" ref="username" placeholder="username"/>
<input type="password" ref="password" placeholder="password"/>
<button type="submit">Submit</button>
</form>
);
}
}
然后我想测试如下:
describe('The SignInForm', () => {
it('should call `attemptSignIn` when submitted with valid data in its input fields', (done) => {
const spy = sinon.stub(flux.getActions('UserStateActions'), 'attemptSignIn');
const element = <SignInForm { ...componentProps }/>;
const component = TestUtils.renderIntoDocument(element);
const inputs = TestUtils.scryRenderedDOMComponentsWithTag(component, 'input');
TestUtils.Simulate.change(inputs[ 0 ], { target: { value: 'Joshua' } });
TestUtils.Simulate.change(inputs[ 1 ], { target: { value: 'Welcome123' } });
// This works, but I'd rather not set the values using the refs directly
// React.findDOMNode(component.refs.userNameOrEmailAddressInput).value = 'Joshua';
// React.findDOMNode(component.refs.plainTextPasswordInput).value = 'Welcome123';
const DOMNode = React.findDOMNode(component, element);
TestUtils.Simulate.submit(DOMNode);
spy.callCount.should.equal(1);
spy.restore();
});
});
但是,onFormSubmit 方法上的引用字段的值不是 Simulate.change 调用设置的值。
为什么不呢?这是预期的行为吗?
【问题讨论】:
-
引用
.value似乎是合理的,因为这是一个测试。事件是由值变化触发的,但值变化不是由事件触发的。
标签: javascript unit-testing testing reactjs reactjs-testutils