mercredi 3 février 2021

How to test onChange event on material UI SelectField with jest & enzyme

this is selectField that i want to test

``

<SelectField> 
  id={'selectFieldForRole'}
  floatingLabelText='Role'
  value={selectedRole}
  onChange={(_, index, value) => {
   this.updateSelectedRole(value);
  }}
>
  {
  frontendConfigFile.ROLE_VALUES_FOR_DEFAULT_BANNERS.map(role => (
  <MenuItem value={role} primaryText={role} />
  ))
  }
</SelectField>

``

the implementation of this.updateSelectedRole is as below.

updateSelectedRole = (value) => {
const selectedArea = frontendConfigFile.ALLOWED_AREAS_FOR_DIFFERENT_ROLES[value][0];
//this above line is throwing error because value is received as undefined. [0] of undefined is resulting //in error
  };

my test case is as below

it('try changing role for banners', () => {
    const component = shallow(
      <BannerView
        getBanner = {getBannerMock}
      />
    );
    const instance = component.instance();
    jest.spyOn(instance, 'updateSelectedRole');
    component.find('#selectFieldForRole').simulate('change', { target: { value: 'ABC' }});
    expect(instance.updateSelectedRole).toHaveBeenCalledTimes(1);
    expect(instance.updateSelectedRole).toHaveBeenCalledWith('COLLEGE');
  });

the actual error that logs in console is

TypeError: Cannot read property '0' of undefined > 138 | const selectedArea = frontendConfigFile.ALLOWED_AREAS_FOR_DIFFERENT_ROLES_FOR_BANNERS[value][0];

please suggest some solution, thanks in advance

Aucun commentaire:

Enregistrer un commentaire