Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing private method using spyOn and Jest

My functions in Calculator class is private and I can't test in this way,

describe('calculate', function() {
  it('add', function() {
    let result = Calculator.Sum(5, 2);
    expect(result).toBe(7);   
  });

  it('substract', function() {
    let result = Calculator.Difference(5, 2);
    expect(result).toBe(3);
  });
});

my class:

export default class calculator {
  private Sum(a: number, b: number): number {
    let c = a + b;
    return c;
  }

  private Difference(a: number, b: number): number {
    let c = a - b;
    return c;
  }
}

how can I modify this test with using spyOn on private methods?

thanks for any help


2 Answers

The easiest solution, to spy on your 'Sum' method of Calculator class, I came around would be:

jest.spyOn(calculator as any, 'Sum').<do-something>();
like image 72
Pauli Avatar answered Sep 13 '25 03:09

Pauli


In Typescript it doesn't allow you to test the private method. So you need something to escape from this behavior. What you can do is something like this

let result = (Calculator as any).Sum(2,3);
expect(result).toBe(5);

I hope that will solve your problem.

like image 44
Abdullah Al Mahmud Avatar answered Sep 13 '25 03:09

Abdullah Al Mahmud