T
T
tostershmoster2021-09-15 07:08:31
Unit testing
tostershmoster, 2021-09-15 07:08:31

How to test a private function?

there is such a function

private createMark(marginFromBegin: number, settings: ISettings): HTMLElement {
  const mark = createElement('span', 'range-slider__scale-mark');

  if (settings.isVertical) {
    mark.className += ' range-slider__scale-mark_vertical';
    mark.style.marginTop = `${marginFromBegin}px`;
  } else {
    mark.style.marginLeft = `${marginFromBegin}px`;
  }

  return mark;
}


write a test for it
import { ISettings } from '../RangeSlider/types';
import Scale from './Scale';

let settings: ISettings;

beforeEach(() => {
  settings = {
    min: 0,
    max: 1500,
    isTwoRunners: true,
    isScaleVisible: true,
    isVertical: false,
    isTooltipsVisible: true,
    valueFrom: 1000,
    valueTo: 1490,
    step: 10,
  };
});

function getPrivateMethod(methodName: string, marginFromBegin: number, settings: ISettings) {
  const scaleProto = Scale.prototype as any;
  const instance = Object.create(scaleProto);
  return () => scaleProto.constructor[methodName].call(instance, marginFromBegin, settings);
}

describe('private createMark method', () => {
  test('should return html element', () => {
    settings.isVertical = true;
    const result = getPrivateMethod('createMark', 100, settings);

    console.log(result);

    expect(result).not.toBeNull();
  });
});


I expect result to be the html element mark which is returned by the createMark function,
but console.log outputs [Function] instead

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-15
@Alexandroppolus

scaleProto.constructor[methodName]
is the method static?
then just take it to the utilities

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question