| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import {fromReturningToBrowserTabEvent} from "./events.util"; |
| |
| describe("EventsUtil", () => { |
| |
| it("should create an Observable which listens to events when returning to the browser tab", () => { |
| const mockedDocument = new MockDocument(document); |
| |
| let hasFired = 0; |
| let error: any = null; |
| let hasFinished = false; |
| |
| const subscription = fromReturningToBrowserTabEvent(mockedDocument.asDocument) |
| .subscribe((e) => hasFired++, (err) => error = err, () => hasFinished = true); |
| |
| expect(hasFired).toBe(0); |
| expect(error != null).toBeFalse(); |
| expect(hasFinished).toBeFalse(); |
| |
| mockedDocument.setToHidden(); |
| mockedDocument.dispatchVisibilityChangeEvent(); |
| |
| expect(hasFired).toBe(0); |
| expect(error != null).toBeFalse(); |
| expect(hasFinished).toBeFalse(); |
| |
| mockedDocument.setToVisible(); |
| mockedDocument.dispatchVisibilityChangeEvent(); |
| |
| expect(hasFired).toBe(1); |
| expect(error != null).toBeFalse(); |
| expect(hasFinished).toBeFalse(); |
| |
| subscription.unsubscribe(); |
| }); |
| |
| }); |
| |
| /** |
| * Mocking class for document to set the visiblity status and dispatch events |
| */ |
| class MockDocument { |
| |
| public constructor(public readonly document: Document) { |
| |
| } |
| |
| public _visibilityState: "hidden" | "visible" = "hidden"; |
| |
| public get visibilityState() { |
| return this._visibilityState; |
| } |
| |
| public get asDocument(): Document { |
| return this as any as Document; |
| } |
| |
| public setToVisible() { |
| this._visibilityState = "visible"; |
| } |
| |
| // Mocked Properties and Methods: |
| |
| public setToHidden() { |
| this._visibilityState = "hidden"; |
| } |
| |
| public dispatchVisibilityChangeEvent() { |
| const event = this.document.createEvent("Event"); |
| event.initEvent("visibilitychange", true, false); |
| this.document.dispatchEvent(event); |
| } |
| |
| public addEventListener(arg1, arg2, arg3?) { |
| return this.document.addEventListener(arg1, arg2, arg3); |
| } |
| |
| public removeEventListener(arg0, arg1, arg2?) { |
| return this.document.removeEventListener(arg0, arg1, arg2); |
| } |
| |
| } |