Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS - testing input action on enter

I have an EmberJS (2.5.0) component similar to the following:

{{input type="text" value=searchValue enter='handleSearch'}}

Basically, hitting enter on the input field should trigger the 'handleSearch' action. And in my component, so far I have this:

searchValue: null,
actions: {
  handleSearch() {
    var searchValue = this.get('searchValue');
    var submitSearch = this.get('submitSearch');
    console.log('Search term entered: ', searchValue);
    if (submitSearch) {
      submitSearch(searchValue);
    }
  }
}

And the component is called via:

{{my-component submitSearch=(action 'externalAction')}}

That all works fine and all, but I'm having trouble actually testing it.

Here's my integration test (pseudo-copied from the guide):

test('search input', function(assert) {
  this.set('externalAction', (actual) => {
    console.log('in external action');
    assert.equal(actual, 'hithere');
  });
  this.render(hbs`{{universal-header-search submitSearch=(action externalAction)}}`);
  this.$('input').val('hithere');
  this.$('input').change();
});

The problem is, my handleSearch action handler never gets triggered. So how do I get my input field to trigger the handler in my integration test? I've also tried this.$('input').submit() and this.$('input').trigger('change'), but neither seems to do anything.

like image 792
accelerate Avatar asked Mar 12 '23 05:03

accelerate


1 Answers

With this.$('input').change(); you are triggering the change event, not the enter event.

After a short research i haven't found a solution to trigger the enter event in integration tests.

You could solve this problem by using the keypress event instead and detect the enter button in your handler (the enter event doesn't exist in jQuery, so i think ember does the same). To get the event in your handler you can't use the ember input helper:

<input type="text" value={{searchValue}} onkeypress={{action "handleSearch"}} />

Your handler:

handleSearch(event) {
  if(event.keyCode === 13) { //check if enter button was pressed
    var searchValue = this.get('searchValue');
    var submitSearch = this.get('submitSearch');
    console.log('Search term entered: ', searchValue);
    if (submitSearch) {
      submitSearch(searchValue);
    }
  }
}

To trigger the keypress event in your integration-test just use

this.$('input').keypress();

Or to trigger keypress event with enter button

var e = jQuery.Event("keypress");
e.which = 13; //enter button code
e.keyCode = 13;
$('input').trigger(e);
like image 145
EnricoB Avatar answered Mar 30 '23 13:03

EnricoB