Search code examples
angulartypescriptngrx

How to write unit test in TypeScript for function inside function?


I am using Angular 16 with the ngRx framework. I develop code using TypeScript. I have to face writing some unit tests (.spec.ts) using Jasmine, for code like the below. How can I call this method in the test class?

export function x1(p1: P1) {
  function xx1(
    tree: T<Code>[],
    code: T<Code>
  ): string | null {
    //some logic
    if(true){
      return "Message";
    } else {
      return null;
    }
  }
  return xx1;
}

In test class

describe('P1', () => {
  const p1 = new P1();
  const validatorFn$ = x1(p1);

  it('should return true', () => {
    // Need to call methiod here
    

  });
});

Solution

  • you can call you validatorFn as any other function:

    const validatorFn = x1(p1);
    var result = validatorFn(parameter1, parameter2)
    

    Functions that returns function are called Higher order functions. You can google that term: https://www.google.com/search?q=higher+order+function+testing&oq=higher+order+function+testing