When reading about TDD you find often sentences like “listen to your tests” or “tests give you feedback about design”. How does it look in practice?

A couple of days ago I interviewed a prospective frontend developer. He submitted the coding assignment and during the on-site interview we kindly asked him to add a new feature to the solution.

The exercise is fairly uncomplicated. You have to display a list of hotels. When a hotel is clicked, its details appear next to the list. The feature to implement was search. Quite simple too – type a text in the box and restrict the list of hotels to the matching ones.

First unit test attempt was like this:

var view = new SearchView();

view.fill('Sunny Palms');

// assert what ???

I was in the navigator role and asked my partner:

“How are you going to check the expected outcome? There is a lot of work to do: we have to access the DOM, extract displayed hotels and verify their names if they match the search pattern.”

I would take us much time to get to a failing test (red lamp in TDD). The test was telling us that we were not on the right way. The component under development probably would have too many responsibilities.

I proposed a different solution. There was already implemented an event bus. The idea was to raise an event and let other component worry about how to handle the search.

The test was quite simple

var eventBus = new EventBus(),
  term;
eventBus.subscribe('search', function (event, data) {
    term = data;
});

view.fill('Sunny Palms');

expect(term).toEqual('Sunny Palms');

We had a failing test. We got to green very quickly – the implementation of the fill method was straightforward.

I wanted to share this story because when I was starting with TDD, the advice “listen to your tests” seemed very awkward. Where do I have to put my ear? Do the tests whisper you that you are wrong? Do they send Morse code? During the programming session I described, it was not a crystal-clear sound. It was a desperate cry for a better design.

Credits to Ky for the “Listen” licensed under CC BY 2.0.

Advertisements