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

  • Drupal CMS Launch Party

    Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!

    | Coven of Wisdom Herentals

    Go to page for Drupal CMS Launch Party
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – 📢 Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creëren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. 📍 Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! 😋 Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 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: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup

Share