{

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


This tutorial covers how to write a 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 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 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.

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.