How to write unit testing static methods in a class of Angular and typescript


In this tutorial, You learned how to do unit test static methods of a typescript classes. It include an example how to test a component using static method in Angular

Let’s declare an ES6 class in typescript with static methods

export class StaticClass {
    static getMessage(name: string): String {
        return 'Hi' + name + 'Welcome to my blog';
    }
}

Here is an Unit test class for ES6 class with static method

  • jasmine API has spyon to mock the methods with instance of a class or a class itself.
  • It accepts arguments with withArgs
  • Return value is returned with returnValue
  • and accepts arguments and return value
  • Unit testing a function is to pass different values
  • And assert followings
    • passed values to static function and compare expected and actual value
    • Check static function is called or not using toHaveBeenCalled method
it('Calling getMessage', () => {
        let spyStaticClass = spyOn(StaticClass, "getMessage")
            .withArgs("John").and.returnValue("welcome");
        StaticClass.getMessage("John")
        expect(StaticClass.getMessage).toHaveBeenCalled();
        expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
        expect(StaticClass.getMessage("John")).toEqual("welcome");

    })

Unit testing Angular component using static method

Suppose you are using an static class in Angular component, In this example, You are calling static method inside ngOnInit() method

import { Component } from '@angular/core';
import { StaticClass } from './StaticClass';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = '';

  constructor() { }

  ngOnInit() {
    this.title = StaticClass.getMessage('john');
  }
}
}

Following is an unit test for given the static function inside a component

it('should call ngInit and call static methods ', () => {

    const fixture = TestBed.createComponent(AppComponent);
    const component = fixture.componentInstance;

    let spyStaticClass = spyOn(StaticClass, "getMessage").and.returnValue("welcome")
    StaticClass.getMessage("John")
    fixture.detectChanges();

    component.ngOnInit();
    expect(StaticClass.getMessage).toHaveBeenCalled();
    expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
    expect(StaticClass.getMessage("John")).toEqual("welcome");
  });

Mock Static method in Jest framework

There are number of ways we can do mock

using jest spyon method which works same as jasmine spyon method.

it('getMessage', () => {
        let spyStaticClass = jest.spyOn(StaticClass, "getMessage")
            .withArgs("John").and.returnValue("welcome");
        StaticClass.getMessage("John")
        expect(StaticClass.getMessage).toHaveBeenCalled();
        expect(StaticClass.getMessage).toHaveBeenCalledWith("John");
        expect(StaticClass.getMessage("John")).toEqual("welcome");

})

Another way is using mock classes with jest implementation

  • Create a mock class for class using jest.Mocked syntax
  • Write a mock implementation for static method
  • Check for assertion of static class is called or not
it('getMessage with jest', () => {
        const MockStaticClass = StaticClass as jest.Mocked<typeof StaticClass>;
        MockStaticClass.getMessage.mockImplementation((item) => 'Welcome' + item);
        expect(MockStaticClass.getMessage).toHaveBeenCalled();

    })

Conclusion

You learned mocking unit testing for static methods inside a es6 classes using jasmine and jest API.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.