javascripttypescriptunit-testing

how to mock class method in unit test in typescript


I have a class with hard private property, how to I mock the value in unit test so I should have something like expect(event.getEventHis()).toBeEqual(['a', 'b'])

export class EventController {
  #event: [];
  constructor() {
    this.#event = [];
    this.#lastIndex = 0;
  }

  getEventHis(): [] {
    return this.#event;
  }

  getLastIndex(): number {
    return this.#lstastIndex;
  }

}
``

Solution

  • You can use jest.spyOn(object, methodName) to mock the getEventHis() method and its returned value.

    E.g.

    index.ts:

    export class EventController {
      #event: string[];
      #lastIndex: number;
    
      constructor() {
        this.#event = [];
        this.#lastIndex = 0;
      }
    
      getEventHis(): string[] {
        return this.#event;
      }
    
      getLastIndex(): number {
        return this.#lastIndex;
      }
    }
    

    index.test.ts:

    import { EventController } from './';
    
    describe('68199289', () => {
      it('should pass', () => {
        jest.spyOn(EventController.prototype, 'getEventHis').mockReturnValueOnce(['a', 'b']);
        const event = new EventController();
        expect(event.getEventHis()).toEqual(['a', 'b']);
      });
    });