Integration-Testing JavaScript with Capybara
Let's learn about integration-testing in JavaScript.
JavaScript integration test difficulty
Nearly every Rails site uses JavaScript for something, and often JavaScript is a critical part of the user experience on sites. However, many sites don’t test their JavaScript in meaningful ways.
Part of the reason is that JavaScript can be difficult to test. Interactions and logic are often dependent on user interaction or the specific state of the elements on the page, which can be hard to set up for testing. The JavaScript frameworks don’t often support easy unit testing. The tools are changing very quickly. The tools we use in this chapter may seem quaint if not downright antiquated by reading this.
That said, some general principles for testing JavaScript will continue to be applicable across tools.
JavaScript testing learning
We’ll learn about JavaScript testing in two parts:
- In this chapter, we’ll learn about using integration-testing tools, specifically Capybara, to test JavaScript from outside the client-side code.
- In the next chapter, we’ll learn about unit-testing JavaScript using JavaScript tools and the new Webpack support in Rails 5.1 or above.
Integration-testing JavaScript with Capybara
In the last chapter, we used Capybara to test buttons in the UI that allowed us to change tasks. As written, clicking upon a task button causes a full server page refresh. This is an interaction that might be more user-friendly if handled client-side with JavaScript.
DOM integration testing
There are multiple ways to handle this client-side. For our purposes, the simplest is to have the up and down buttons manipulate the browser DOM to change the order and send an update request to the server to register the other change. We need to test two things: that the client interaction actually changes the DOM and that the changes are sent back to the server accurately.
We want to split the integration test for adding a task into one spec that adds the task and one test that handles the reordering. This isolates the JavaScript to just the task that handles reordering:
Get hands-on with 1400+ tech skills courses.