2017-09-24 5 views
1

質問:getBreakpoint()内からgetWindowSizeの参照を取得するにはどうすればいいですか?その後、私は呼び出して偽のデータを返す必要がありますか?jasmineを使用して、関数を監視し、別の関数の内部からモック値を返すにはどうすればよいですか?

メディア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) 
    }) 
    }) 

UPDATE:ジャスミンはspysを行うためにbeableする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

私は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})

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, 
    ]; 
    } 
} 
関連する問題