我有以下缩写反应组件
render() {
return (
<div className={styles.srchBoxContaner}>
<input
className={styles.incSrchTextBox}
type="text" name="search" placeholder="Search.."
onChange={this.onChange}
/>
</div>
);
}
现在我想对它进行单元测试,特别是我想模拟输入并确保调用onChange
我如何使用Enzyme和Jest来做到这一点。到目前为止,这是我提出的
it('calls \'onPerformIncrementalSearch\' when the user types in something', () => {
const incrementalSearchWrapper = mount(<IncrementalSearch />);
const onChangeSpy = sinon.spy(IncrementalSearch.prototype, 'onChange');
//find the input element
const searchInput = incrementalSearchWrapper.find('#search');
searchInput.simulate('change', { target: { value: 'new search value' } });
expect(IncrementalSearch.prototype.onChange.called).toEqual(true);
onChangeSpy.restore();
});
然而,这似乎不起作用。
答案 0 :(得分:0)
以防其他人遇到此问题,修复方法是在调用mount之前移动间谍。所以工作代码是
const onChangeSpy = sinon.spy(IncrementalSearch.prototype, 'onChange');
const incrementalSearchWrapper = mount(<IncrementalSearch />);
// find the input element
const searchInput = incrementalSearchWrapper.find('#searchInput');
searchInput.node.value = 'David';
searchInput.simulate('change', searchInput);
expect(onChangeSpy.called).toEqual(true);
onChangeSpy.restore();