Published September 27, 2015 by Toran Billups

Earlier this year ember-qunit introduced the ability to test components in isolation. At first I didn't know what all the hype was about but as I began writing more and more components I found this type of test was extremely valuable for anyone building large apps. One of the biggest wins is that you don't need to spin up the entire app like a traditional acceptance test would so they provide blazing fast feedback.

When I first started writing integration tests I didn't realize how much I would miss the mature helper library that has been shipping with ember since 1.3 (visit/fillIn,andThen). I had to re-learn how I would interact with the DOM manually in test code. I found that I was able to ramp up quickly and learn the basics but one tricky problem presented itself a few weeks back that I wanted to write about.

I was adding a multiselect and needed a way to "alter" the selected items but using val would always deselect anything already highlighted. I asked around but not a single person had blogged about this issue so here goes :)

The select component

If you haven't seen a simple multiselect it looks something like this

To make it a little more ember component friendly I've added an onchange that lets me pass the user model in addition to the selected role id (target.value in the below -gives us the "value" of the selected option). I also added a quick in-list helper to know if something is selected (using a simple in-memory list for this example).

The integration test

In the first iteration I pass along the required data, render the component, and ask how many are selected

The failing test

Like anyone hacking the DOM I tried using $component.val but quickly found that my test was now failing because it only had one item selected.

The solution

I found using the special prop("selected", true) would keep my original item selected, while truly adding another!

If you want the full blown sample project with a handful of other tests/validation/identity map/ember 2.1/etc checkout this project on github.