【发布时间】:2017-09-24 16:48:38
【问题描述】:
问题:我如何从 getBreakpoint() 内部获取 getWindowSize 的引用,以便我可以对其进行监视?之后需要调用Fake并返回mock数据?
媒体查询.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 ];
});
}
媒体查询.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 使用猴子补丁来进行间谍活动。我只需要一个猴子补丁可以存在的范围,所以如果我将我的函数设为一个类,它可以按预期工作:
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,
];
}
}
【问题讨论】:
标签: javascript unit-testing typescript jasmine