简体   繁体   English

单元测试使用Jest,Enzyme对变化做出反应

[英]Unit testing react component on change with Jest, Enzyme

I have the following abbreviated react component 我有以下缩写的react组件

   render() {
        return (
            <div className={styles.srchBoxContaner}>
                <input
                    className={styles.incSrchTextBox}
                    type="text" name="search" placeholder="Search.."
                    onChange={this.onChange}
                />
            </div>
        );
    }

Now I want to unit test this, specifically I want to simulate an input and make sure onChange is called 现在我要对此进行单元测试,特别是我想模拟一个输入并确保调用了onChange。

How do I do this using Enzyme, and Jest. 如何使用酶和笑话来做到这一点。 So far this is what I have come up with 到目前为止,这是我想出的

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();
});

However this does not seem to work. 但是,这似乎不起作用。

Just in case someone else runs into this problem, the fix was to move the spy up before calling mount. 以防万一其他人遇到此问题,解决方法是在调用mount之前将间谍向上移动。 So the working code is 所以工作代码是

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM