A great friend (an incredibly talented developer) and I were drinking some excellent whiskey recently, and we got to talking about junior developers starting on teams where TDD is well-established. There is a huge amount written on the subject, there are multiple flavours and there are also a huge number of frameworks that support writing better tests. This can be overwhelming when the fundamentals are quite simple, and the “attitude” can get lost in the deluge of information and opinions. My friend suggested that it would be great to have an article he could point new people to, which would lay-out a very simple but very detailed test-driven example, using as few frameworks as possible. This would help keep the TDD message clear. Here I attempt to deliver a very basic example using Javascript.
Trying to introduce a new methodology to an organisation comprising technical and non-technical stakeholders can be difficult. Having good justifications on-hand can be incredibly helpful and so here I’d like to provide four business justifications for TDD with which I have previously had success.
Test frameworks like Mocha and Karma make testing your Javascript code trivial. They provide expressive assertion patterns, make it easy to mock dependencies and they run anywhere which makes them great for CI. Testing your React components, however, can be difficult because much of the functionality of your component happens during the render lifecycle. This means that in order to simulate actions and make assertions on your component’s behaviour, you must write (potentially a lot of) DOM interrogation code. This can lead to large tests which in turn reduces the expressiveness of those tests, and their ability to clearly describe the behaviour of your application. Enzyme is the solution.