Speedup unit tests development in Angular with NG-Mocks

By Alexey Ses

2 min read

There are multiple ways to speed up unit tests development in Angular. Let me show two of them using the NG-Mocks library.

Speedup unit tests development in Angular with NG-Mocks
Authors

Why does it take so much time to create unit tests?

Unit tests are an important part of any application. However, the development of robust unit tests takes time. One of the things that takes a lot of that time is mocking all the dependencies. Angular CLI doesn't help you a lot, because it only generates the initial .spec file with default TestBed configuration. So how can you speed up unit test development in Angular?

Mock the dependencies with NG-Mocks library

NG-Mocks is a testing library that helps to mock all the dependencies. It has plenty of helper functions. I would like to show you two of them that might help you the most.

Speedup TestBed module configuration with MockProvider function

Each component or service might depend on other components and services. Here's an example of a service that depends on HttpClient, Router and OAuthService:

auth.service.ts
@Injectable({
    providedIn: 'root',
})
export class AuthService {
    constructor(
        private http: HttpClient,
        private router: Router,
        private oauthService: OAuthService,
    ) {
        this.configureSSO();
    }

    /**
     * OAuthService needs to be configured in order to use its Single Sign-On feature
     */
    private configureSSO() {
        this.oauthService.configure(authConfig);
        this.oauthService.tokenValidationHandler = new JwksValidationHandler();
        this.oauthService.loadDiscoveryDocumentAndTryLogin();
    }

    loginWithSSO(): void {
        // ...
    }

    logoutWithSSO(): void {
        // ...
    }

    loginUserAndRedirect(): Observable<boolean> {
        return this.http.post('http://localhost:4200/', 'some payload').pipe(
            switchMap(() => {
                this.router.navigate(['/dashboard']);
                return of(true);
            }),
        );
    }
}

Let's implement the test config for that service. The default approach would be to use the TestBed.configureTestingModule() function to configure all the dependencies. What needs to be passed into that function:

  1. HttpClientTestingModule, which configures HttpClientTestingBackend used by HttpClient.
  2. Mock of OAuthService.
auth.service.spec.ts
describe('AuthService', () => {
  let service: AuthService;
  let router: Router;
  let httpMock: HttpTestingController;
  let oAuthService: OAuthService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: OAuthService,
          useValue: {
            configure: () => {},
            loadDiscoveryDocumentAndTryLogin: () => {},
            tokenValidationHandler: new JwksValidationHandler(),
          },
        },
      ],
    });

    router = TestBed.inject(Router);
    httpMock = TestBed.inject(HttpTestingController);
    oAuthService = TestBed.inject(OAuthService);
    service = TestBed.inject(AuthService);
  });
});

At least two tests need to be added. Both of them would contain spyOn functions to detect when a specific method gets called on an instance of a specific class:

auth.service.spec.ts
describe('AuthService', () => {
    let service: AuthService;
    let router: Router;
    let httpMock: HttpTestingController;
    let oAuthService: OAuthService;

    beforeEach(() => {...});

    it('should configure SSO on initialization ', () => {
        // Arrange
        const configureSpy = spyOn(oAuthService, 'configure');
        const tokenValidationHandlerSpy = spyOnProperty(oAuthService, 'tokenValidationHandler', 'set');
        const loadDiscoveryDocumentAndTryLoginSpy = spyOn(oAuthService, 'loadDiscoveryDocumentAndTryLogin');
        const httpClientSpy: HttpClient = jasmine.createSpyObj(['post']);

        // Act
        new AuthService(httpClientSpy, router, oAuthService);

        // Assert
        expect(configureSpy).toHaveBeenCalledWith(authConfig);
        expect(tokenValidationHandlerSpy).toEqual(new JwksValidationHandler());
        expect(loadDiscoveryDocumentAndTryLoginSpy).toHaveBeenCalled();
    });

    it('should send a POST request to the server and navigate to "/dashboard" on success', () => {
        // Arrange
        const navigateSpy = spyOn(router, 'navigate');

        // Act
        service.loginUserAndRedirect().subscribe();

        // Assert
        const req = httpMock.expectOne('http://localhost:4200/');
        expect(req.request.method).toBe('POST');
        req.flush({}); // Simulate a successful response

        expect(navigateSpy).toHaveBeenCalledWith(['/dashboard']);
    });
});

Now let's replace the mock of OAuthService in TestBed with NG-Mocks MockProvider helper function:

auth.service.spec.ts
beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        providers: [MockProvider(OAuthService)],
    });

    //...
});

MockProvider(OAuthService) creates empty dummies as methods of OAuthService which is totally ok for implemented tests.

Spy all methods of services using ngMocks.autoSpy

ngMocks.autoSpy is an awesome feature if you want to get rid of all spied methods in your tests. In order to use it in the specific test, it needs to be added on top of the .spec file:

auth.service.spec.ts
ngMocks.autoSpy('jasmine');

describe('AuthService', () => {
    //...
})

After that tests need to be updated:

auth.service.spec.ts
ngMocks.autoSpy('jasmine');

describe('AuthService', () => {
    let service: AuthService;
    let router: Router;
    let httpMock: HttpTestingController;
    let oAuthService: OAuthService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [MockProvider(OAuthService), MockProvider(Router)],
        });

        router = TestBed.inject(Router);
        httpMock = TestBed.inject(HttpTestingController);
        oAuthService = TestBed.inject(OAuthService);
        service = TestBed.inject(AuthService);
    });

    it('should configure SSO on initialization ', () => {
        // Assert
        expect(oAuthService.configure).toHaveBeenCalledWith(authConfig);
        expect(oAuthService.tokenValidationHandler).toEqual(new JwksValidationHandler());
        expect(oAuthService.loadDiscoveryDocumentAndTryLogin).toHaveBeenCalled();
    });

    it('should send a POST request to the server and navigate to "/dashboard" on success', () => {
        // Act
        service.loginUserAndRedirect().subscribe();

        // Assert
        const req = httpMock.expectOne('http://localhost:4200/');
        expect(req.request.method).toBe('POST');
        req.flush({}); // Simulate a successful response

        expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
    });
});

As you can see, now it's a bit less code in the tests.

Make tests more maintainable

One more exciting thing from NG-Mocks is a proposal on how to make tests more maintainable. The idea is to write tests without scoped variables. Basically, specific arrangements need to be applied to specific tests so that each test is self-sufficient and does not rely on scoped variables:

auth.service.spec.ts
ngMocks.autoSpy('jasmine');

describe('AuthService', () => {
    let service: AuthService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [MockProvider(OAuthService), MockProvider(Router)],
        });

        service = TestBed.inject(AuthService);
    });

    it('should configure SSO on initialization ', () => {
        // Arrange
        const oAuthService = TestBed.inject(OAuthService);

        // Assert
        expect(oAuthService.configure).toHaveBeenCalledWith(authConfig);
        expect(oAuthService.tokenValidationHandler).toEqual(new JwksValidationHandler());
        expect(oAuthService.loadDiscoveryDocumentAndTryLogin).toHaveBeenCalled();
    });

    it('should send a POST request to the server and navigate to "/dashboard" on success', () => {
        // Arrange
        const httpMock = TestBed.inject(HttpTestingController);
        const router = TestBed.inject(Router);

        // Act
        service.loginUserAndRedirect().subscribe();

        // Assert
        const req = httpMock.expectOne('http://localhost:4200/');
        expect(req.request.method).toBe('POST');
        req.flush({}); // Simulate a successful response

        expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
    });
});

As you can see now arrangements are applied to specific tests. That should make them more maintainable as we add other tests into that .spec file.

Conclusion

I hope NG-Mocks will help you with unit test development and improve your overall developer experience as you create Angular applications. Happy coding!


Upcoming events

  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tรผtรผncรผ, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! ๐Ÿš€ 18:00 โ€“ ๐Ÿšช Doors open to the public 18:15 โ€“ ๐Ÿ• Letโ€™s eat 19:00 โ€“ ๐Ÿ“ข Getting Your Axe On Event Sourcing with Axon Framework 20:00 โ€“ ๐Ÿน Small break 20:15 โ€“ ๐Ÿ“ข Event-Driven Microservices - Beyond the Fairy Tale 21:00 โ€“ ๐Ÿ™‹โ€โ™€๏ธ drinks 22:00 โ€“ ๐Ÿป See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many โ€œmicroservices projectsโ€ fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! ๐Ÿš€ 18:00 โ€“ ๐Ÿšช Doors open to the public 18:15 โ€“ ๐Ÿ• Letโ€™s eat 19:00 โ€“ ๐Ÿ“ข First round of Talks 19:45 โ€“ ๐Ÿน Small break 20:00 โ€“ ๐Ÿ“ข Second round of Talks 20:45 โ€“ ๐Ÿ™‹โ€โ™€๏ธ drinks 21:00 โ€“ ๐Ÿป See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup
  • Coven of Wisdom - Herentals - Spring `24 edition

    Join us for an exciting web technology meetup where youโ€™ll get a chance to gain valuable insights and knowledge about the latest trends in the field. Donโ€™t miss out on this opportunity to expand your knowledge, network with fellow developers, and discover new and exciting possibilities. And the best part? Food and drinks are on us! Johan Vervloet - Event sourced wiezen; an introduction to Event Sourcing and CQRS Join me on a journey into the world of CQRS and Event Sourcing! Together we will unravel the misteries behind these powerful concepts, by exploring a real-life application: a score app for the 'Wiezen' card game.Using examples straight from the card table, we will delve into the depths of event sourcing and CQRS, comparing them to more traditional approaches that rely on an ORM.We will uncover the signs in your own database that indicate where event sourcing can bring added value. I will also provide you with some tips and pointers, should you decide to embark on your own event sourcing adventure. Filip Van Reeth - WordPress API; "Are you talking to me?" What if the WordPress API could be one of your best friends? What kind of light-hearted or profound requests would it share with you? In this talk, I would like to introduce you to it and ensure that you become best friends so that together you can have many more pleasant conversations (calls). Wanna be friends? Please note that the event or talks will be conducted in Dutch. Want to give a talk? Send us your proposal at meetup.herentals@iodigital.com 18:00 - 19:00: Food/Drinks/Networking 19:00 - 21:00: Talks 21:00 - 22:00: Networking Thursday 30th of May, 18h00 - 22h00 CET iO Campus Herentals, Zavelheide 15, Herentals

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Spring `24 edition

Share