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


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

Private methods are private to same class. It is not allowed to access outside can be only accessed in public methods of an typescript class.

Angular unit testing for private methods

Let’s declare an 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 an private method which is accesable 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 Employee class

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

        employee.calculateSalary();
    })
}

Angular unit testing for static methods

static methods are directly accessible with class names.

And instance of the class are 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 an class in typescript and angular.

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.