Posts

Showing posts from March, 2023

How to Verify Observables are Unsubscribed to in Angular Unit Tests

In most cases, when you subscribe to an Observable , you should also unsubscribe  from it. In Angular, there are a few exceptions (for example, Observables returned by HttpClient ), but usually unsubscribing is the way to go. But how would you write a unit test to make sure this happens? One way is by using a  Subject . A Subject is a kind of Observable. It includes an observed  property which is a boolean and indicates whether or not it is being subscribed to. Prior to this, there was an observers  property which provided a count of observers, but this has been deprecated. In the test below, the component being tested contains code to ensure that JobListenerService.jobCompleted  Observable is being unsubscribed to when the component's ngOnDestroy()  method is called. The mock of the service returns a Subject  (a type of Observable), and we use that Subject to verify that it's being observed before the component is destroyed, but no longer being observ...

Architectural Considerations for Angular Applications

Image
When it comes to application architecture, my approach is holistic: it's not just about the application design, but the things around  the application -- for example, unit tests and linting -- that can help produce a solid application.  Here are some of my thoughts for creating successful Angular applications, though many of these apply to other sorts of applications as well. The goal is to design something in such a way that it's easy to maintain, easy to enhance, avoids pitfalls, and most importantly, works as intended . Here we go! 1. Use those spec files Angular was designed from the start with unit testing in mind. But a lot of Angular developers I've spoken to don't use the spec files the CLI creates for us. Having good code coverage is important, and it's worth taking the time to write those unit tests. For more information on how unit testing has helped me write better software, check out  this post. 2. Organize code into judicious feature modules with lazy-...