Posts Tagged ‘mocha’

Testing select fields in Mocha

Thursday, October 10th, 2013 | Programming

Recently I spent a good twenty minutes tearing my hair out over a JavaScript unit test I was trying to write. The answer turned out to be a difference in the way our Mocha-based DOM differs from how it would running JavaScript in a browser.

For example, let’s say you have a select field.

<select name="test" id="test">
	<option value="">Select an option</option>
	<option value="1">Option 1</option>
	<option value="2">Option 2</option>
</select>

In a browser, the top option would be selected by default, so if you had the following code:

jQuery('#test').val();

It would output a blank value as you would expect. However, run this in Mocha and you will get an undefined or a null. The reason is Mocha doesn’t select the top option by default unless you manually specify it to. So your HTML would have to look like:

<select name="test" id="test">
	<option value="" selected="selected">Select an option</option>
	<option value="1">Option 1</option>
	<option value="2">Option 2</option>
</select>

In which case, it would then return the value as it should.