Kevin
Kevin

Reputation: 15974

How do I get the text of an <option> component?

I'm writing a test that tests a function that outputs an array of <option> Components. I want to test that the <option>s have the correct values and display the correct text.

I can check the value of each <option> like so:

const generatedArrayOfOptionComponents = functionToTest();
const firstOptionComponent = generatedArrayOfOptionCompononts[0];
const optionValue = firstOptionComponent.props.value;

How can I get the text that firstOptionComponent will show when it is rendered?


Answers to similar questions typically involve adding an event handler and getting the text of the selected <option> when it changes. This won't work for me because I'm in a testing environment. In this test, all I have are the Component objects returned by the test - there's no DOM environment, and this particular test doesn't use Enzyme. How can I get the <option> component's text from the raw component instance itself?

Upvotes: 0

Views: 47

Answers (1)

Hamms
Hamms

Reputation: 5107

There are a couple of situations in which it's nice to interact with the rendered products of a React component in a situation where you don't have a DOM; tests are one, isomorphic serverside React is another, and I'm sure there are more.

In those situations, ReactDOMServer is there for you.

Upvotes: 1

Related Questions