Jest testcase for dropdown on 2nd item selection

2.2k views Asked by At

I am trying to write testcase for dropdown which I have done in stenciljs.

HTML

<div>
   <select class="form-control user-dropdown">
     <option value="" disabled selected={this.userItem === undefined}>      
         Choose option</option>
       {this.dropdownList.map(items =>
           <option value={items.userId}>{items.userValue)</option>}
</select>
</div>

where

userItem:{userId: string, userValue: string} = {userId:"101" , userValue: "Dean"} and
dropdownList is array of above object

in the test case I have created a query selector but I am not able to select 2nd dropdown so that I can check .toEqual()

const page = await newSpecPage({
   component: [MyComponent],
   html: '<my-component></my-component>'
});
page.rootInstance.userItem= {userId:"101" , userValue: "Dean"}
page.rootInstance.dropdownList= [{userId:"101" , userValue: "Dean"}, {userId:"102" , userValue: "Maze"}....];

await.page.waitForChange();
const ele=page.root.querySelector('select[name="dropdown"]');

// here I want to change dropdown so that I can check value

expect(ele......).toEqual('102');

Any idea how to select 2nd dropdown option so that I can test expected value?

1

There are 1 answers

0
Rahul On

I don't think you can do that with a Jest spec test, but you can do it with an e2e test. The code below shows how.. The interesting bit is await page.find('your-component >>> .user-dropdown'). the >>> is a shadow dom piercing selector which lets you query for elements within your component's shadow root.

import { newE2EPage } from '@stencil/core/testing';

describe('conponent e2e test', () => {
  it('renders', async () => {
    const page = await newE2EPage();
    await page.setContent('<your-component></your-component>');

    const userItem = {userId:'101' , userValue: 'Dean'}
    const dropdownList = [{userId:'101' , userValue: 'Dean'}, {userId:'102' , userValue: 'Maze'}];

    await page.$eval('your-component', (elm: any, {userItem, dropdownList}) => {
      // within the browser's context
      // let's set new property values on the component
      elm.userItem = userItem;
      elm.dropdownList = dropdownList;
    }, {userItem, dropdownList});

    await page.waitForChanges();

    const element = await page.find('your-component');
    expect(element).toHaveClass('hydrated');

    const selectList = await page.find('your-component >>> .user-dropdown');
    const options = await selectList.findAll('option');
    expect(options.length).toBe(3);
    expect(options[2].getAttribute('value')).toBe('102');

  });
});