1

Question: I how do I get the reference of getWindowSize from inside getBreakpoint() so I may put a spy on it? After which, I need to callFake and return mock data?

media-query.ts

export const widthBasedBreakpoints: Array<number> = [
  576,
  768,
  992,
  1200,
  1599,
];
export function getWindowSize() {
  return {
    h: window.innerHeight,
    w: window.innerWidth,
  };
}

export function getBreakpoint() {
  const { w: winWidth } = getWindowSize();

  return widthBasedBreakpoints.find((bp, idx, arr) => {
    return winWidth <= bp && idx === 0
      ? true
      : winWidth >= arr[ idx - 1 ];
  });
}

media-query.spec.ts

  import * as MQ from './media-query';
  describe('getBreakpoint()', ()=> {
    it('should return a breakpoint', ()=> {
      expect(MQ.getBreakpoint()).toBeTruthy();
    });
    it('should return small breakpoint', ()=> {
      spyOn(MQ, 'getWindowSize').and.callFake(()=> {w: 100});
      expect(MQ.getBreakpoint()).toBe(576)
    })
  })

UPDATE: Jasmine uses monkeypatching to beable to do spys. I just need a scope that the monkey patching can live on so if I make my functions a class this works as intended:

export class MediaQueryHelper {
  public static getWindowSize() {
    return {
      h: window.innerHeight,
      w: window.innerWidth,
    };
  }
  public static getBreakpoint() {
    const { w: winWidth } = MediaQueryHelper.getWindowSize();

    return MediaQueryHelper.getBreakpoints().find((bp, idx, arr) => {
      return winWidth <= bp && idx === 0
        ? true
        : winWidth >= arr[ idx - 2 ]
    });
  }
  public static getBreakpoints(): Array<number> {
    return [
      576,
      768,
      992,
      1200,
      1599,
    ];
  }
}
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233

2 Answers2

0

The only solution I can offer you from here is this:

export const widthBasedBreakpoints: Array<number> = [
  576,
  768,
  992,
  1200,
  1599,
];
export function getWindowSize(win = window) {
  return {
    h: win.innerHeight,
    w: win.innerWidth,
  };
}

export function getBreakpoint(win = window) {
  const { w: winWidth } = getWindowSize(win);

  return widthBasedBreakpoints.find((bp, idx, arr) => {
    return winWidth <= bp && idx === 0
      ? true
      : winWidth >= arr[ idx - 1 ];
  });
}

And then do your tests using getBreakpoint({innerHeight: h, innerWidth: w})

lilezek
  • 6,976
  • 1
  • 27
  • 45
0
export class MediaQueryHelper {
  public static getWindowSize() {
    return {
      h: window.innerHeight,
      w: window.innerWidth,
    };
  }
  public static getBreakpoint() {
    const { w: winWidth } = MediaQueryHelper.getWindowSize();

    return MediaQueryHelper.getBreakpoints().find((bp, idx, arr) => {
      return winWidth <= bp && idx === 0
        ? true
        : winWidth >= arr[ idx - 2 ]
    });
  }
  public static getBreakpoints(): Array<number> {
    return [
      576,
      768,
      992,
      1200,
      1599,
    ];
  }
}
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233