How to write unit testing for private and static in Angular and typescript

This tutorial covers how to write unit testing for private methods in Angular applications.

Private methods are private to the same class. It does not allow access outside in public methods of a typescript class.

Writing Angular unit testing for private methods

Let’s declare a class.

export class Employee{
    private calculateSalary(){
        console.log("Private method to calculate salary")
    }
    public getTotalSalary(){
        console.log("Return total salary of an employee")
    }
}

calculateSalary() is a private method that is accessible in public method getTotalSalary().

const employee = new Employee();

console.log(employee.getTotalSalary()); // this works
console.log(employee.calculateSalary()); // 'private'

Let’s see how to write a unit test for the Employee class.

describe("Employee Class") {
    let employee:Employee;
    it('private method test', () => {
         employee = new Employee();
        const employeeObj = Object.getPrototypeOf(employee);

        employee.calculateSalary();
    })
}

Writing unit testing for static methods in Angular

Static methods are directly accessible with class names.

And an instance of the class is not required to access static, unlike objects.

export class Employee {
  static getTotalSalary() {
    console.log("Return total salary of an employee");
  }
}

Unit test cases for static method in typescript

describe("Employee Class") {
    it('static method test', () => {
        Employee.getTotalSalary();
    })
}

We can also use spy-on static methods.

Conclusion

In this tutorial, you learned how to write a unit test for private and static methods of a class in typescript and angular.