Skip to content

Instantly share code, notes, and snippets.

@jeffsheets
Last active December 30, 2023 23:30
Show Gist options
  • Save jeffsheets/49bfbc28d11b2565f39fcc89fb231def to your computer and use it in GitHub Desktop.
Save jeffsheets/49bfbc28d11b2565f39fcc89fb231def to your computer and use it in GitHub Desktop.
testing-library set and get a react-select value
import React from 'react';
import { screen, render } from '@testing-library/react';
import selectEvent from 'react-select-event';
import CountryComponent from './FakeComponent';
describe('CountryComponent Test', () => {
test('form has value of selected option', async () => {
render(<CountryComponent />);
// react-select let's us update the select value by label, but you must select it by role 'textbox' not a 'select'
await selectEvent.select(screen.getByRole('textbox', {name: 'Country'}), 'USA', {
container: () => document.body
});
// react-select does not put an id on the <input type="hidden" name="country" value="USA"/> field to link it to the label.
// the label points to a textbox that is used to select values but doesn't store the value in it.
// So we cannot get the form value via the label.
// Instead we can get it from the form itself by form field name.
// (note: The form needs to have a name on it to get the aria role of form: <form name="contactForm" ......>)
expect((new FormData(screen.getByRole('form'))).get('country')).toBe('USA');
// For comparison, text fields are easier:
expect(screen.getByRole('textbox', { name: 'City' })).toHaveValue('Omaha');
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment