Query: How can I access the reference of getWindowSize within getBreakpoint() to perform spying on it? Additionally, how can I use callFake to 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: In Jasmine, monkeypatching is used for spys. By converting my functions into a class, this method works correctly:
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,
];
}
}