6 Testing frontend applications

 

This chapter covers

  • Replicating a browser’s JavaScript environment in your tests
  • Asserting on DOM elements
  • Handling and testing events
  • Writing tests involving browser APIs
  • Handling HTTP requests and WebSocket connections

Trying to write a client-side application without using JavaScript is as difficult as baking a dessert without carbohydrates. JavaScript was born to conquer the web, and in browsers, it has shone.

In this chapter, we’ll cover the fundamentals of testing frontend applications. Together, we’ll build a small web client for the backend we wrote in chapter 4 and learn how to test it.

During the process of building and testing this application, I’ll explain the peculiarities of running JavaScript within a browser, and, because Jest can’t run in a browser, I’ll teach you how to simulate that environment within Node.js. Without being able to emulate a browser’s environment in Jest, you wouldn’t be able to use it to test your frontend applications.

When testing frontend applications, assertions can become more challenging, because now you’re dealing not only with a function’s return value but also with its interaction with the DOM. Therefore, you will learn how to find elements within your tests and perform assertions on their contents.

6.1 Introducing JSDOM

6.2 Asserting on the DOM

6.2.1 Making it easier to find elements

6.2.2 Writing better assertions

6.3 Handling events

6.4 Testing and browser APIs

6.4.1 Testing a localStorage integration

6.4.2 Testing a History API integration

6.5 Dealing with WebSockets and HTTP requests

6.5.1 Tests involving HTTP requests

6.5.2 Tests involving WebSockets

Summary