How to simulate select event during stencil tests?

17 views Asked by At

I have a simple Stencil component like this:

@Component({
  tag: 'app-select',
  shadow: false
})
export class AppSelect {
  render() {
    return (
      <select>
        <slot></slot>
      </select>
    );
  }
}

which is used in another simple component:

@Component({
  tag: 'app-my-comp',
  shadow: true,
})
export class AppComp {
  selectPageNumber(event): void {
    store.page = Number(event.target.value);
  }

  render() {
    return (
      <app-select id="page-navigation" onInput={e => this.selectPageNumber(e)}>
            <option value="1">1</option>
            <option value="2">2</option>
      </app-select>
    );
  }
}

and I would like to test a page selection.

describe('testing project footer component', () => {
    let page: SpecPage;
    let mainEl: HTMLElement;

    beforeEach(async () => {
        page = await newSpecPage({
            components: [AppComp, AppSelect],
            html: '<app-my-comp></app-my-comp>'
        });

        mainEl = page.body.querySelector('app-my-comp').shadowRoot;
    });

        it('should work', async () => {
            const pageSelector: HTMLSelectElement = mainEl.querySelector('#page-navigation');
            pageSelector.dispatchEvent(new Event('input'));
            await page.waitForChanges();

            expect(store.page).toBe(1);
        });
});

How do I specify target.value of event? With the debugger, I noticed that I receive a MockEvent and every reflection trick is not working.

Do you have any idea?

1

There are 1 answers

0
G. Tranter On

You don't specify target on an Event - it is a read only property. The target is the element that dispatched the event.

The problem with your code is:

const pageSelector: HTMLSelectElement = mainEl.querySelector('#page-navigation');

and

store.page = Number(event.target.value);

#page-navigation is an <app-select> element not <select> and it does not have a value property. You need to add a value Prop to the component as well as fix your type usage.