问题:我如何从getBreakpoint()内部获取getWindowSize的引用,以便我可以对它进行间谍检查?之后,我需要调用Fake并返回模拟数据吗?
媒体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 ];
});
}
媒体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)
})
})
更新:Jasmine使用monkeypatching来做间谍活动。我只需要一个猴子修补可以使用的范围,所以如果我使我的函数成为一个类,它按预期工作:
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,
];
}
}
答案 0 :(得分:0)
我可以从here向您提供的唯一解决方案是:
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 ];
});
}
然后使用getBreakpoint({innerHeight: h, innerWidth: w})
答案 1 :(得分: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,
];
}
}