【发布时间】:2016-03-19 20:19:54
【问题描述】:
我正在尝试为我的组件测试事件,但未调用提交处理程序。除了事件之外,我所有的单元测试都在工作。我正在使用 Tape、Sinon 和 JSDOM,并在网上四处寻找有类似问题的人。有一个类似问题的 Github 问题,但我不能 100% 确定它是否完全相同。 https://github.com/facebook/react/issues/1185 SO 上还有一个相关的post,但它没有帮助,因为他们使用的是浅层渲染。
测试:
// Create a document using JSDOM
const document = createDocument();
let output;
const onSubmitHandler = spy();
// Render the DOM
output = renderDOM(
<ToDoCreate
onSubmit={onSubmitHandler}
/>,
document.body);
const form = TestUtils.findRenderedDOMComponentWithTag(output, 'form');
// Simulate a submit
TestUtils.Simulate.submit(form);
const actual = onSubmitHandler.callCount;
const expected = 1;
// Test the event handler was called
assert.equal(actual, expected);
assert.end();
结果:
# ToDoCreate component
# ...submitted form to create a ToDo
not ok 14 should be equal
---
operator: equal
expected: 1
actual: 0
...
有没有人知道为什么这不起作用?
谢谢
更新:添加 ToDoCreate 的 render() 输出
<form className={toDoCreateClasses} onSubmit={this._handleToDoCreateSubmit}>
<div className="form-group">
<label className="sr-only">New ToDo</label>
<input type="text" className="form-control ToDoInput" ref="title" placeholder="Add a new ToDo..." />
</div>
<button type="submit" className="btn btn-primary">Add</button>
</form>
更新:添加 _handleToDoCreateSubmit 方法
_handleToDoCreateSubmit(e) {
e.preventDefault();
// Get the ToDo title
let title = this.refs.title.value;
// Validate
if ( title === '' ) {
window.alert('You need to enter a ToDo first :)');
return false;
}
// Trigger the submit event
ToDoDispatcher.dispatch({
actionType: 'TODO_CREATE_SUBMIT',
title: title
});
// Clear the Dom node
this.refs.title.value = '';
}
【问题讨论】:
-
onSubmit是如何连接到form的? -
@DavinTryon 我刚刚用渲染方法的输出更新了这个问题。
-
这是其中的一部分,但我想看看你在哪里使用
this.props.onSubmit。现在这似乎发生在_handleToDoCreateSubmit方法中。我们也能看到吗? -
@DavinTryon 确定,添加在上面:)
标签: javascript unit-testing reactjs tdd sinon