TDD in Javascript
Learn about TDD, DOM, and Jasmine unit testing JavaScript and how to write Jasmine tests.
TDD unit testing JavaScript example
Now let’s try to build the task-rearrangement feature in JavaScript using TDD. We’ll use a different approach to JavaScript than we did in the previous chapter, and we’ll be completely rewriting the JavaScript Task
class. First, we’ll build the logic without regard to how the application will get data into the JavaScript objects and how they will interact with the DOM. Approaching the feature this way allows us to focus on the code and not the large external dependencies of the server-side data and the DOM.
We still have the Capybara integration test from Testing JavaScript Integration Testing. Whatever we do here, that test should still work (or at least, should work pending minor changes based on changing DOM structure). So we can think of this process as a slightly different instance of outside-in testing. The Capybara test is still the outside test, but instead of using RSpec to write server-side tests, we’re using Jasmine to write client-side tests.
DOM unit testing JavaScript
We should note that this is a minimal feature, and we’re probably overbuilding it based on the current requirements, but it is handy to see a small example. In practice, the idea of using tests to isolate the JavaScript from the server and the DOM becomes more compelling the more logic is needed in the client. In practice, a larger example would likely use a framework like React or Vue that uses data binding to help isolate logic from the DOM.
Single-page apps
We’ll end up with a Project
and a Test
class on the client that is dissimilar to the ones we already have on the server. This duplication is a common problem in web applications, and there isn’t a clear solution. One solution is to move all the logic to the client and write a single-page web app backed by a simple server. This may be the right solution in some cases. Usually, unless the client has a lot of interactivity, the client’s single-page app winds up being more complicated than an app that has some logic on the server, some logic on the client, and some duplication. We realize that sounds counterintuitive.
Jasmine unit testing JavaScript
Here’s the first batch of Jasmine tests (note that we did write and get these to pass one at a time):
Get hands-on with 1400+ tech skills courses.