简体   繁体   中英

how to mock hard private property in class 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;
  }

}
``

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

Eg

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']);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM