Simulating pressing Enter on a button in a test

I have a component with a button and a click handler. In my test, I’m trying to simulate pressing Enter on the button, but it won’t fire the click handler. However when I manually do it, it does. Any ideas?

ember g component my-button -gc
<button type="button" {{on "click" this.onClick}}>
  Press enter on me
</button>
import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class MyButtonComponent extends Component {
  @action
  onClick() {
    console.log('BOOM');
  }
}
module('Integration | Component | my-button', function (hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function (assert) {
    await render(hbs`<MyButton />`);

    await focus('button');
    await triggerKeyEvent('button', 'keydown', 'Enter');
  });
});

The result of the test is that it doesn’t log “BOOM”. However, if I manually do it in the browser, “BOOM” is logged. Any ideas? Thanks in advance!

in your component, it has bound the click event. In the browser, pressing Enter eventually emits this click event as well.

Using the click() helper from @ember/test-helpers will be sufficient, because otherwise you’re testing that the browser implemented Enter presses correctly :sweat_smile:

1 Like

Doesn’t the click test helper trigger a click event? How can you test hitting ‘enter’ with it?

1 Like

enter triggers a click event as well.

See this vanilla JS demo: JS Bin - Collaborative JavaScript Debugging

1 Like

Wow, thanks, I wasn’t aware! :clap: