![](/img/trans.png)
[英]How to mock "window.location.origin" in jasmine unit test angular6
[英]How to mock window.screen.width in Angular Unit Test with Jasmine
我有一個 BreakpointService,它告訴我 - 取決於屏幕寬度 - 我應該在哪個 SidebarMode(關閉 - 縮小 - 打開)中顯示我的側邊欄。
這是服務的主要部分:
constructor(private breakpointObserver: BreakpointObserver) {
this.closed$ = this.breakpointObserver.observe(['(min-width: 1024px)']).pipe(
filter((state: BreakpointState) => !state.matches),
mapTo(SidebarMode.Closed)
);
this.opened$ = this.breakpointObserver.observe(['(min-width: 1366px)']).pipe(
filter((state: BreakpointState) => state.matches),
mapTo(SidebarMode.Open)
);
const minifiedStart$: Observable<boolean> = this.breakpointObserver.observe(['(min-width: 1024px)']).pipe(map(state => state.matches));
const minifiedEnd$: Observable<boolean> = this.breakpointObserver.observe(['(max-width: 1366px)']).pipe(map(state => state.matches));
this.minified$ = minifiedStart$.pipe(
flatMap(start => minifiedEnd$.pipe(map(end => start && end))),
distinctUntilChanged(),
filter(val => val === true),
mapTo(SidebarMode.Minified)
);
this.observer$ = merge(this.closed$, this.minified$, this.opened$);
}
通過這一行,我可以訂閱事件:
this.breakpointService.observe().subscribe();
現在,我想在單元測試中測試不同的模式,但我不知道
如何在測試中模擬 window.screen.width 屬性
我嘗試了幾件事,但對我來說沒有任何效果。
到目前為止,這是我的測試設置:
describe('observe()', () => {
function resize(width: number): void {
// did not work
// window.resizeTo(width, window.innerHeight);
// (<any>window).screen = { width: 700 };
// spyOn(window, 'screen').and.returnValue(...)
}
let currentMode;
beforeAll(() => {
service.observe().subscribe(mode => (currentMode = mode));
});
it('should return Observable<SidebarMode>', async () => {
resize(1000);
expect(Object.values(SidebarMode).includes(SidebarMode[currentMode])).toBeTruthy();
});
xit('should return SidebarMode.Closed', async () => {
resize(600);
expect(currentMode).toBe(SidebarMode.Closed);
});
xit('should return SidebarMode.Minified', async () => {
resize(1200);
expect(currentMode).toBe(SidebarMode.Minified);
});
xit('should return SidebarMode.Open', async () => {
resize(2000);
expect(currentMode).toBe(SidebarMode.Open);
});
});
我猜 BreakPointObserver 會監聽 resize 事件,所以也許您可以嘗試使用 jasmine 模擬 window.innerWidth / window.outerWidth 之類的東西?
spyOnProperty(window, 'innerWidth').and.returnValue(760);
然后您手動觸發調整大小事件:
window.dispatchEvent(new Event('resize'));
它看起來像這樣:
it('should mock window inner width', () => {
spyOnProperty(window, 'innerWidth').and.returnValue(760);
window.dispatchEvent(new Event('resize'));
});
BreakpointObserver
我猜你不是真的想模擬 window.screen,你實際上想模擬BreakpointObserver
。 畢竟,不需要測試他們的代碼,您只想測試您的代碼是否正確響應BreakpointObserver.observe()
返回的具有不同屏幕尺寸的 observable。
有很多不同的方法可以做到這一點。 為了說明一種方法,我將STACKBLITZ與您的代碼放在一起,展示了我將如何處理此問題。 與上面的代碼不同的注意事項:
resize()
的調用發生在service = TestBed.get(MyService);
之前service = TestBed.get(MyService);
稱呼。BreakpointObserver
與spyObj,並呼吁在地方的假冒功能BreakpointObserver.observe()
方法。 這個假函數使用了我設置的過濾器,其中包含我想要的各種匹配結果。 它們都以 false 開始,因為這些值會根據需要模擬的屏幕尺寸而改變,而這是由您在上面的代碼中使用的resize()
函數設置的。注意:當然還有其他方法可以解決這個問題。 在 github 上查看 angular 材料自己的
breakpoints-observer.spec.ts
。 這是一種比我在這里概述的更好的通用方法,它只是為了測試您提供的功能。
這是來自 StackBlitz 的新建議describe
函數的片段:
describe(MyService.name, () => {
let service: MyService;
const matchObj = [
// initially all are false
{ matchStr: '(min-width: 1024px)', result: false },
{ matchStr: '(min-width: 1366px)', result: false },
{ matchStr: '(max-width: 1366px)', result: false },
];
const fakeObserve = (s: string[]): Observable<BreakpointState> =>
from(matchObj).pipe(
filter(match => match.matchStr === s[0]),
map(match => ({ matches: match.result, breakpoints: {} })),
);
const bpSpy = jasmine.createSpyObj('BreakpointObserver', ['observe']);
bpSpy.observe.and.callFake(fakeObserve);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [MyService, { provide: BreakpointObserver, useValue: bpSpy }],
});
});
it('should be createable', () => {
service = TestBed.inject(MyService);
expect(service).toBeTruthy();
});
describe('observe()', () => {
function resize(width: number): void {
matchObj[0].result = width >= 1024;
matchObj[1].result = width >= 1366;
matchObj[2].result = width <= 1366;
}
it('should return Observable<SidebarMode>', () => {
resize(1000);
service = TestBed.inject(MyService);
service.observe().subscribe(mode => {
expect(
Object.values(SidebarMode).includes(SidebarMode[mode]),
).toBeTruthy();
});
});
it('should return SidebarMode.Closed', () => {
resize(600);
service = TestBed.inject(MyService);
service
.observe()
.subscribe(mode => expect(mode).toBe(SidebarMode.Closed));
});
it('should return SidebarMode.Minified', () => {
resize(1200);
service = TestBed.inject(MyService);
service
.observe()
.subscribe(mode => expect(mode).toBe(SidebarMode.Minified));
});
it('should return SidebarMode.Open', () => {
resize(2000);
service = TestBed.inject(MyService);
service.observe().subscribe(mode => expect(mode).toBe(SidebarMode.Open));
});
});
});
如果您查看 BreakpointObserver 的測試,您會得到答案。 您不需要模擬 BreakpointObserver,您需要模擬注入其中的 MediaMatcher。 這是我的一項測試。
let mediaMatcher: FakeMediaMatcher;
class FakeMediaQueryList {
/** The callback for change events. */
private listeners: ((mql: MediaQueryListEvent) => void)[] = [];
constructor(public matches: boolean, public media: string) {}
/** Toggles the matches state and "emits" a change event. */
setMatches(matches: boolean): void {
this.matches = matches;
/** Simulate an asynchronous task. */
setTimeout(() => {
// tslint:disable-next-line: no-any
this.listeners.forEach((listener) => listener(this as any));
});
}
/** Registers a callback method for change events. */
addListener(callback: (mql: MediaQueryListEvent) => void): void {
this.listeners.push(callback);
}
/** Removes a callback method from the change events. */
removeListener(callback: (mql: MediaQueryListEvent) => void): void {
const index = this.listeners.indexOf(callback);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
}
@Injectable()
class FakeMediaMatcher {
/** A map of match media queries. */
private queries = new Map<string, FakeMediaQueryList>();
/** The number of distinct queries created in the media matcher during a test. */
get queryCount(): number {
return this.queries.size;
}
/** Fakes the match media response to be controlled in tests. */
matchMedia(query: string): FakeMediaQueryList {
const mql = new FakeMediaQueryList(true, query);
this.queries.set(query, mql);
return mql;
}
/** Clears all queries from the map of queries. */
clear(): void {
this.queries.clear();
}
/** Toggles the matching state of the provided query. */
setMatchesQuery(query: string, matches: boolean): void {
const mediaListQuery = this.queries.get(query);
if (mediaListQuery) {
mediaListQuery.setMatches(matches);
} else {
throw Error('This query is not being observed.');
}
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
{ provide: MediaMatcher, useClass: FakeMediaMatcher },
],
});
});
beforeEach(inject([MediaMatcher], (mm: FakeMediaMatcher) => {
mediaMatcher = mm;
}));
afterEach(() => {
mediaMatcher.clear();
});
describe('get isSideNavClosable$', () => {
beforeEach(() => {
// (Andrew Alderson Jan 1, 2020) need to do this to register the query
component.isSideNavClosable$.subscribe();
});
it('should emit false when the media query does not match', (done) => {
mediaMatcher.setMatchesQuery('(max-width: 1280px)', false);
component.isSideNavClosable$.subscribe((closeable) => {
expect(closeable).toBeFalsy();
done();
});
});
it('should emit true when the media query does match', (done) => {
mediaMatcher.setMatchesQuery('(max-width: 1280px)', true);
component.isSideNavClosable$.subscribe((closeable) => {
expect(closeable).toBeTruthy();
done();
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.