user 9191
user 9191

Reputation: 747

OnBlur not getting called the right way - jest enzyme

Here is the code that I am trying to test

updateUser = (e) => {
  var tempUser = this.state.user;
  switch(e.target.id){
    case "email":
      tempUser.Email = e.target.value;
      break;
    case "userName":
      tempUser.Username = e.target.value;
      break;
    default:
      break;
  }

  this.setState({
    user: tempUser,
  })

render() {
.....
  <tr key='userName' className='add-user-table-row'>
  <input id='userName' onBlur={this.updateUser} className='user-value-field' defaultValue=''/> </td>

And here is my test: The test passes at the moment but is not affecting its coverage. Any reason ? Thanks

it('Testing the userName onBlur', () => {
  wrapper.setState({
    user:{
      Username:'Username-Test'
    }
  });
  wrapper.find('input[id="userName"]').simulate('blur', {target: { value:'Username-Test'}});
  expect(wrapper.state('user')).toEqual('Username-Test'); //remove this line??
});

Upvotes: 2

Views: 1544

Answers (2)

skyboyer
skyboyer

Reputation: 23725

Since your code checks for id:

updateUser = (e) => {
  var tempUser = this.state.user;
  switch(e.target.id){
  ...
  case "userName":
    tempUser.Username = e.target.value;

You need to pass appropriate id otherwise case will not match

wrapper.find('input[id="userName"]')
  .simulate('blur', {
    target: { 
      value:'Username-Test', 
      id: 'userName'
    }
  });

Upvotes: 1

kgriffiths
kgriffiths

Reputation: 21

You could try force updating the wrapper

it('Testing the userName onBlur', (done) => {
  wrapper.setState({
    user: {
      Username: 'Username-Test'
    }
  });

  process.nextTick(() => {
    wrapper.update();
    wrapper.find('input[id="userName"]').simulate('blur', {
      target: {
        value: 'Username-Test'
      }
    });
    expect(wrapper.state('user')).toEqual('Username-Test');
    done();
  })
});

Upvotes: 2

Related Questions