'Test onBlur event in React component using Jest/Enzyme not firing
I am testing the onBlur event in the Textbox(a child component inside BasePartnerRegistrationForm that's connected to redux store). I tried all means in SOF posts but the console always shows below. Is it really the onBlur event not firing? How can I debug this to find out what is causing the root problem? Is there other things that possibly not letting me testing the onBlur...
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
class BasePartnerRegistrationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
ages: [],
};
}
componentDidMount() {
this.createExperiences();
}
createExperiences() {
let experiences = [
{ value: '', text: 'First time order?' },
{ value: 'yes', text: 'Yes' },
{ value: 'no', text: 'No' },
{ value: 'not sure', text: "I'm not sure" },
];
this.setState({ experiences: experiences });
}
checkUserByEmail(elemName, value) {
getUserByEmail(value)
.then((results) => {
let showLoginNote = true;
let notifications = document.getElementsByClassName('message');
__forEach(notifications, (message) => {
if (__startsWith(message.textContent, 'It looks like you have an account')) {
showLoginNote = false;
return false;
}
});
if (!__isEmpty(results) && showLoginNote) {
notify('info', 'It looks like you have an account. Click here to log in.', 0, () => {
this.props.history.push('/login');
});
}
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<div>
<div data-type="email" className="textbox-wrapper">
<Textbox
type="email"
placeholder="Email Address"
name="register-email"
onChange={this.setEmail}
onBlur={this.checkUserByEmail}
defaultValue={this.state.email}
/>
</div>
</div>
);
}
}
const mapDispatchToProps = { saveEmail };
export default connect(null, mapDispatchToProps)(BasePartnerRegistrationForm);
my test case:
it('calls checkUserByEmail when the Textbox for email is onBlur', () => {
const checkUserByEmailSpy = jest.spyOn(BasePartnerRegistrationForm.WrappedComponent.prototype, 'checkUserByEmail');
const wrapper = mount(
<Provider store={store}>
<BasePartnerRegistrationForm {...baseProps} />
</Provider>
);
const onBlurEvent = wrapper.find('Textbox').at(0);
onBlurEvent.simulate('blur', { target: { name: 'register-email' } });
expect(checkUserByEmailSpy).toHaveBeenCalled();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
