5 Testing front-end applications

 

In this chapter:

  • 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 front-end applications. Together, we’ll build a small web client for the back-end we’ve written 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. Without being able to emulate a browser’s environment in Jest, you wouldn’t be able to use it to test your front-end applications.

When testing front-end applications, assertions can become more challenging, because now you’re not only dealing 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.

5.1 Introducing JSDOM

5.2 Asserting on the DOM

5.2.1 Making it easier to find elements

5.2.2 Writing better assertions

5.3 Handling events

5.4 Testing and browser APIs

5.4.1 Testing a localStorage integration

5.4.2 Testing a History API integration

5.5 Dealing with web sockets and HTTP requests

5.5.1 Tests involving HTTP requests

5.5.2 Tests involving web-sockets

5.6 Summary