问题
I am trying to press enter on one of the input boxes. Doing it manually triggers the event listener, however, while trying with enzyme, the event listener is not triggered. What am I doing wrong here?
Event Listener
this.input.addEventListener('keypress', function(event){
debugger;
onEnter(event);
});
Enzyme
function setup(store, props) {
return mount(<Provider store={store}>
<component{...props}/>
</Provider>
);
}
beforeEach(() => {
wrapper = setup(store, {});
searchBar = wrapper.find('searchBar');
searchInput = searchBar.find("input");
});
it("when enter is pressed, event should be triggered", ()=> {
let wait = false;
runs(()=> {
searchInput.simulate('change', {target: {value: 'helloWorld'}});
searchInput.simulate('keyPress', {which: 13});
setTimeout(()=> {
wait = true;
}, 1000);
})
waitsFor(()=> {
return wait;
}, "", 1500);
})
回答1:
I was struggling with this problem too. But now I`ve found a solution.
In addition to { which: 13 }
parameter, you need to specify at least key
parameter, so your simulate expression will be like:
searchInput.simulate('keyPress', {
key: 'Enter',
keyCode: 13,
which: 13,
});
回答2:
Enzyme, built for React testing, likely doesn't know about your native JavaScript event listener. If you bind the event with JSX, Enzyme should be able to pick it up. https://reactjs.org/docs/handling-events.html
Change this:
this.input.addEventListener('keypress', function(event){
debugger;
onEnter(event);
});
To this:
<searchBar>
<input onKeypress={this.onEnter.bind(this)} aria-label="Search" />
</searchBar>
来源:https://stackoverflow.com/questions/46067048/enzyme-wrapper-find-simulate-keypress-doesnt-trigger-event-listener