Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Angular Cookbook - Second Edition

You're reading from  Angular Cookbook - Second Edition

Product type Book
Published in Dec 2023
Publisher Packt
ISBN-13 9781803233444
Pages 536 pages
Edition 2nd Edition
Languages
Author (1):
Muhammad Ahsan Ayaz Muhammad Ahsan Ayaz
Profile icon Muhammad Ahsan Ayaz

Table of Contents (16) Chapters

Preface 1. Winning Component Communication 2. Working with Angular Directives and Built-In Control Flow 3. The Magic of Dependency Injection in Angular 4. Understanding Angular Animations 5. Angular and RxJS – Awesomeness Combined 6. Reactive State Management with NgRx 7. Understanding Angular Navigation and Routing 8. Mastering Angular Forms 9. Angular and the Angular CDK 10. Writing Unit Tests in Angular with Jest 11. E2E Tests in Angular with Cypress 12. Performance Optimization in Angular 13. Building PWAs with Angular 14. Other Books You May Enjoy
15. Index

Writing Unit Tests in Angular with Jest

“It works on my machine” is a phrase that won’t lose its beauty with time. It is a shield for many engineers and a nightmare for the quality assurance professionals. But honestly, what’s a better way for your application’s robustness than writing tests? And when it comes to writing unit tests, my personal favorite is Jest. That is because it is super-fast, lightweight, and has an easy API to write tests. More importantly, it is faster than the Karma and Jasmine setup that comes out of the box with Angular. In this chapter, you’ll learn how to configure Jest with Angular to run these tests in parallel. You’ll learn how to test components, services, and pipes with Jest. You’ll also learn how to mock dependencies for these tests.

In this chapter, we’re going to cover the following recipes:

  • Setting up unit tests in Angular with Jest
  • Providing global mocks for Jest...

Technical requirements

For the recipes in this chapter, ensure your setup is complete as per the 'Technical Requirements' in the 'Angular-Cookbook-2E' GitHub repository. For setup details, visit: https://github.com/PacktPublishing/Angular-Cookbook-2E/tree/main/docs/technical-requirements.md. The starter code for this chapter is located at https://github.com/PacktPublishing/Angular-Cookbook-2E/tree/main/start/apps/chapter10.

Setting up unit tests in Angular with Jest

By default, a new Angular project comes bundled with a lot of goodness, including the configuration and tooling in which to run unit tests with Karma and Jasmine. While working with Karma is relatively convenient, many developers find that in large-scale projects, the whole testing process becomes much slower if there are a lot of tests involved. This is mainly because you can’t run tests in parallel. In this recipe, we’ll set up Jest for unit testing in an Angular app. Additionally, we’ll migrate existing tests from the Karma syntax to the Jest syntax.

Starting with v16, Angular comes with a developer preview for Jest, and the process has become much easier. This recipe targets apps up to Angular v15 and covers what we can do in v16 at the end of the chapter.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-jest-setup inside the cloned repository:

...

Providing global mocks for Jest

In the previous recipe, we learned how to set up Jest for Angular unit tests. There might be some scenarios in which you’d want to use a browser API that might not be part of your actual Angular code – for instance, using LocalStorage or alert. In such cases, we need to provide some global mocks for the functions that we want to return mock values from. This is so that we can perform tests involving them as well. In this recipe, you’ll learn how to provide global mocks to Jest.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-jest-global-mocks inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-jest-global-mocks
    

    This should open the app in a new browser tab, and you should see the following...

Mocking Angular services using stubs

There’s rarely an Angular app that doesn’t have a Service created inside it. And where overall business logic is concerned, services hold a great deal, particularly when it comes to interacting with APIs. In this recipe, you’ll learn how to mock services using stubs.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-test-services-stubs inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-test-services-stubs
    

    This should open the app in a new browser tab, and you should see the following:

    Figure 10.6: The ng-test-services-stubs app running on http://localhost:4200

Now that we have the app running locally, in the next section, let’s take a look at the steps of the recipe...

Using spies on an injected service in a unit test

While you can provide stubs for your services in the unit tests with Jest, sometimes, it might feel like an overhead creating a mock for every new service. Let’s suppose that if the service’s usage is limited to one test file, it might make more sense to just use spies on the actual injected service. In this recipe, that’s exactly what we’re going to do.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-test-services inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-test-services
    

    This should open the app in a new browser tab, and you should see the following:

    Figure 10.8: ng-test-services app running on http://localhost:4200

Now that we have the app...

Mocking child components and directives using the ng-mocks package

Unit tests mostly revolve around testing components, directives, pipes, or services in isolation. However, what if your component depends completely on another component or directive to work properly, especially in a non-standalone application/component? In such cases, you usually provide a mock implementation for the component, but that is a lot of work. However, with the ng-mocks package, it is super-easy. In this recipe, we’ll learn an advanced example of how to use ng-mocks for a parent component that depends on a child component to work properly.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-test-ng-mocks inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-test-ng-mocks
    
    ...

Writing even easier tests with Angular CDK component harnesses

When writing tests for components, there might be scenarios where you’d want to interact with the DOM elements. Now, this can already be achieved by using the fixture.debugElement.query method to find the element, using a selector and then triggering events on it. However, that means maintaining the DOM queries for different platforms, knowing the identifiers of all the selectors, and then exposing all of that in the tests. And this is even worse if we’re talking about an Angular library. It certainly isn’t necessary for each developer who interacts with my library to know all the element selectors in order to write tests. Only the author of the library should know that much to respect encapsulation. Luckily, we have the component harnesses from the Angular CDK team, which were released with Angular 9 along with the IVY compiler. And they’ve led by example, by providing component harnesses for...

Unit-testing responses from HTTP calls

If you’re building an Angular application, it is very likely that you’ll work with HTTP calls inside the app at some point. For instance, you could be fetching data from a third-party API or just making APIs to your own server. In either case, it becomes slightly difficult to test applications that have HTTP calls in action. In this recipe, we’re going to learn how to create unit-tests with HTTP calls.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-test-http-resp inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-test-http-resp
    

    This should open the app in a new browser tab, and you should see the following:

    Figure 10.14: The ng-test-http-resp app running on http://localhost...

Unit-testing Angular pipes

In my opinion, pipes are the easiest thing to test in an Angular application. Why? Well, this is because they’re (supposed to be) pure functions that return the same result based on the same set of inputs. In this recipe, we’ll write some tests for a simple pipe in an Angular application.

Getting ready

The app that we are going to work with now resides in start/apps/chapter10/ng-test-pipes inside the cloned repository:

  1. Open the code repository in your code editor.
  2. Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
    npm run serve ng-test-pipes
    

    This should open the app in a new browser tab, and you should see the following:

    Figure 10.18: The ng-test-pipes app running on http://localhost:4200

Now that we have the app running locally, in the next section, let’s go through the steps of the recipe.

How to do it....

lock icon The rest of the chapter is locked
You have been reading a chapter from
Angular Cookbook - Second Edition
Published in: Dec 2023 Publisher: Packt ISBN-13: 9781803233444
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}