UNPKG

@wdio/visual-service

Version:

Image comparison / visual regression testing for WebdriverIO

72 lines (71 loc) 2.63 kB
import logger from '@wdio/logger'; import { DEVICE_RECTANGLES } from '@wdio/image-comparison-core'; import { getNativeContext } from './utils.js'; const log = logger('@wdio/visual-service:ContextManager'); export class ContextManager { #browser; #needsUpdate = false; #currentContext; #isNativeContext; cachedViewport = DEVICE_RECTANGLES; constructor(browser) { this.#browser = browser; const capabilities = this.#browser.requestedCapabilities; this.#isNativeContext = getNativeContext({ capabilities, isMobile: this.#browser.isMobile }); this.#browser.on('result', this.#onCommandResult.bind(this)); } getViewportContext() { return this.cachedViewport; } setViewPortContext(viewport) { this.cachedViewport = viewport; this.#needsUpdate = false; } get browser() { return this.#browser; } get needsUpdate() { return this.#needsUpdate; } markForUpdate() { this.#needsUpdate = true; } setCurrentContext(context) { this.#currentContext = context; if (this.#browser.isMobile) { this.#isNativeContext = context ? context === 'NATIVE_APP' : this.#isNativeContext; } } async getCurrentContext() { return this.#currentContext; } get isNativeContext() { return this.#isNativeContext; } async #onCommandResult(event) { const commands = ['switchAppiumContext', 'switchContext', 'setOrientation']; if (commands.includes(event.command)) { const { body: { name, orientation }, result } = event; // Check if result exists and is not an error object // @ts-expect-error const isSuccess = result && !result.error && typeof result === 'object'; if (isSuccess) { if (event.command === 'setOrientation') { log.info(`Device rotation to "${orientation}" detected, context will need recalculation.`); this.markForUpdate(); } else { if (name && name !== 'NATIVE_APP') { log.info(`Context changed to "${name}", context will need recalculation.`); this.markForUpdate(); } // Set the context to the current context this.setCurrentContext(name); } } else { log.warn('Orientation set failed: \n', result, '\nWe could not recalibrate the context'); } } } }