How to use unwrapParams method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

protocol.js

Source:protocol.js Github

copy

Full Screen

...235 jsonObj = wrapParams(spec.payloadParams, jsonObj);236 }237 // unwrap params if necessary238 if (spec.payloadParams && spec.payloadParams.unwrap) {239 jsonObj = unwrapParams(spec.payloadParams, jsonObj);240 }241 if (spec.command === CREATE_SESSION_COMMAND) {242 // try to determine protocol by session creation args, so we can throw a243 // properly formatted error if arguments validation fails244 currentProtocol = determineProtocol(...makeArgs(req.params, jsonObj, spec.payloadParams || {}));245 }246 // ensure that the json payload conforms to the spec247 checkParams(spec.payloadParams, jsonObj, currentProtocol);248 // turn the command and json payload into an argument list for249 // the driver methods250 let args = makeArgs(req.params, jsonObj, spec.payloadParams || {}, currentProtocol);251 let driverRes;252 // validate command args according to MJSONWP253 if (validators[spec.command]) {...

Full Screen

Full Screen

1.7_wrap_unwrap_uniV3.js

Source:1.7_wrap_unwrap_uniV3.js Github

copy

Full Screen

1require("dotenv").config();2const config = require('../config.json');3const { expect } = require('chai');4const { waffle } = require("hardhat");5const provider = waffle.provider;6const abi = require('human-standard-token-abi');7const { deployWrappersOnly, log } = require('./helper');8const { toUtf8Bytes } = require("ethers/lib/utils");9const addr = config.addresses;10const { Pool, nearestUsableTick, Position } = require('@uniswap/v3-sdk');11const { Token } = require('@uniswap/sdk-core');12const abi_uniswap = require('./abis/uniswapV3Pool.json');13const abi_position_manager = require('./abis/positionManager.json');14const poolAddress = "0x4e68Ccd3E89f51C3074ca5072bbAC773960dFa36";15const poolImmutablesAbi = [16 "function factory() external view returns (address)",17 "function token0() external view returns (address)",18 "function token1() external view returns (address)",19 "function fee() external view returns (uint24)",20 "function tickSpacing() external view returns (int24)",21 "function maxLiquidityPerTick() external view returns (uint128)",22];23describe('Deploying the plexus contracts for WrapperUni adding liquidity test', () => {24 let wrapper, owner;25 let netinfo;26 let network = 'unknown';27 let tokenPairAddress = '';28 let daiTokenAddress;29 let sushiTokenAddress;30 let compoundTokenAddress;31 let wethAddress;32 const unitAmount = "2";33 // Deploy and setup the contracts34 before(async () => {35 const { deployedContracts } = await deployWrappersOnly();36 wrapper = deployedContracts.wrapperUniV3;37 owner = deployedContracts.owner;38 addr1 = deployedContracts.addr1;39 netinfo = await ethers.provider.getNetwork();40 network = netinfo.chainId === 1 ? "mainnet" :41 netinfo.chainId === 42 ? "kovan" :42 netinfo.chainId === 56 ? "binance" :43 netinfo.chainId === 137 ? "matic" : 'mainnet';44 daiTokenAddress = addr.tokens.DAI[network];45 usdtTokenAddress = addr.tokens.USDT[network];46 usdcTokenAddress = addr.tokens.USDC[network];47 farmTokenAddress = addr.tokens.FARM[network];48 pickleTokenAddress = addr.tokens.PICKLE[network];49 sushiTokenAddress = addr.tokens.SUSHI[network];50 compoundTokenAddress = addr.tokens.COMP[network];51 wethAddress = addr.tokens.WETH[network];52 });53 async function getPoolImmutables(poolContract) {54 const PoolImmutables = {55 factory: await poolContract.factory(),56 token0: await poolContract.token0(),57 token1: await poolContract.token1(),58 fee: await poolContract.fee(),59 tickSpacing: await poolContract.tickSpacing(),60 maxLiquidityPerTick: await poolContract.maxLiquidityPerTick(),61 };62 console.log(PoolImmutables);63 return PoolImmutables;64 }65 async function getPoolState(poolContract) {66 const [liquidity, slot] = await Promise.all([67 poolContract.liquidity(),68 poolContract.slot0(),69 ]);70 const PoolState = {71 liquidity,72 sqrtPriceX96: slot[0],73 tick: slot[1],74 observationIndex: slot[2],75 observationCardinality: slot[3],76 observationCardinalityNext: slot[4],77 feeProtocol: slot[5],78 unlocked: slot[6],79 };80 console.log(PoolState);81 return PoolState;82 }83 describe('Test Uni V3 liquidity pool', () => {84 it('Should convert 2 ETH to USDT Token(s) from MakerDao via Uniswap', async () => {85 const zeroAddress = process.env.ZERO_ADDRESS;86 const userSlippageTolerance = config.userSlippageTolerance;87 const daiToken = new ethers.Contract(usdtTokenAddress, abi, provider);88 const poolContract = new ethers.Contract(89 poolAddress,90 abi_uniswap,91 provider92 );93 94 const [immutables, state] = await Promise.all([95 getPoolImmutables(poolContract),96 getPoolState(poolContract),97 ]);98 const TokenB = new Token(3, immutables.token0, 6, "USDT", "USD Tether");99 const TokenA = new Token(3, immutables.token1, 18, "WETH", "Wrapped Ether");100 const poolExample = new Pool(101 TokenA,102 TokenB,103 immutables.fee,104 state.sqrtPriceX96.toString(),105 state.liquidity.toString(),106 state.tick107 );108 console.log(poolExample);109 const tickLower = nearestUsableTick(state.tick, immutables.tickSpacing) - immutables.tickSpacing * 2;110 const tickUpper = nearestUsableTick(state.tick, immutables.tickSpacing) + immutables.tickSpacing * 2;111 console.log("tick lower %s - tick Upper %s", tickLower, tickUpper);112 const types = ['address', 'uint24', 'address']113 const values = [114 wethAddress,115 3000,116 usdtTokenAddress]117 const encodedKey = ethers.utils.defaultAbiCoder.encode(types, values)118 const incentiveId = ethers.utils.keccak256(encodedKey)119 // Please note, the number of dai tokens we want to get doesn't matter, so the unit amount is just a placeholder120 const amountPlaceholder = ethers.utils.parseEther(unitAmount)121 // We send 2 ETH to the wrapper for conversion122 let overrides = {123 value: ethers.utils.parseEther("3")124 };125 // Convert the 2 ETH to Dai Token(s)126 const deadline = Math.floor(new Date().getTime() / 1000) + 1000;127 const paths = [usdtTokenAddress];128 const path = [incentiveId, incentiveId];129 let wrapParams = {130 sourceToken: zeroAddress,131 destinationTokens: paths,132 paths: path,133 amount: amountPlaceholder,134 minAmounts: [0, 0],135 poolFee: 3000,136 tickLower: tickLower,137 tickUpper: tickUpper,138 userSlippageTolerance: userSlippageTolerance,139 deadline: deadline,140 };141 const { status } = await (await wrapper.connect(addr1).wrap(wrapParams, overrides)).wait();142 expect(status).to.equal(1);143 // Check conversion is successful144 if (status === 1) {145 // Check the dai token balance in the contract account146 const daiTokenBalance = Number(ethers.utils.formatUnits(await daiToken.balanceOf(addr1.address), 6));147 // Check if the conversion is successful and the user has some dai tokens in their wallet148 log("User USDT Token balance AFTER ETH conversion: ", daiTokenBalance);149 expect(daiTokenBalance).to.be.gt(0);150 // Check that the users ETH balance has reduced regardless of the conversion status151 const ethBalance = Number(ethers.utils.formatEther(await addr1.getBalance()));152 log('User ETH balance AFTER ETH conversion is: ', ethBalance);153 }154 });155 it('Should wrap USDT Token(s) to (ETH-USDT) via UniswapV3', async () => {156 const zeroAddress = process.env.ZERO_ADDRESS;157 const userSlippageTolerance = config.userSlippageTolerance;158 const daiToken = new ethers.Contract(usdtTokenAddress, abi, provider);159 const poolContract = new ethers.Contract(160 poolAddress,161 abi_uniswap,162 provider163 );164 165 const [immutables, state] = await Promise.all([166 getPoolImmutables(poolContract),167 getPoolState(poolContract),168 ]);169 const TokenB = new Token(3, immutables.token0, 6, "USDT", "USD Tether");170 const TokenA = new Token(3, immutables.token1, 18, "WETH", "Wrapped Ether");171 const poolExample = new Pool(172 TokenA,173 TokenB,174 immutables.fee,175 state.sqrtPriceX96.toString(),176 state.liquidity.toString(),177 state.tick178 );179 console.log(poolExample);180 const tickLower = nearestUsableTick(state.tick, immutables.tickSpacing) - immutables.tickSpacing * 2;181 const tickUpper = nearestUsableTick(state.tick, immutables.tickSpacing) + immutables.tickSpacing * 2;182 console.log("tick lower %s - tick Upper %s", tickLower, tickUpper);183 const types = ['address', 'uint24', 'address']184 const values = [185 usdtTokenAddress,186 3000,187 zeroAddress]188 189 const encodedKey = ethers.utils.defaultAbiCoder.encode(types, values)190 //const encodedKey = ethers.utils.defaultAbiCoder.encodePacked(usdtTokenAddress,3000, zeroAddress)191 //abi.encodePacked(DAI, poolFee, WETH9);192 const incentiveId = ethers.utils.keccak256(encodedKey)193 // We send 2 ETH to the wrapper for conversion194 let overrides = {195 value: ethers.utils.parseEther("3")196 };197 let daiTokenBalance = await daiToken.balanceOf(addr1.address);198 // Convert the 2 ETH to Dai Token(s)199 const deadline = Math.floor(new Date().getTime() / 1000) + 1000;200 const paths = [usdtTokenAddress, zeroAddress];201 const path = [incentiveId, "0xdac17f958d2ee523a2206206994597c13d831ec7000bb8c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"];202 console.log(path[0]);203 let wrapParams = {204 sourceToken: usdtTokenAddress,205 destinationTokens: paths,206 paths: path,207 amount: daiTokenBalance,208 minAmounts: [0, 0],209 poolFee: 3000,210 tickLower: tickLower,211 tickUpper: tickUpper,212 userSlippageTolerance: userSlippageTolerance,213 deadline: deadline,214 };215 await daiToken.connect(addr1).approve(wrapper.address,daiTokenBalance );216 const { status } = await (await wrapper.connect(addr1).wrap(wrapParams)).wait();217 expect(status).to.equal(1);218 // Check conversion is successful219 if (status === 1) {220 // Check the dai token balance in the contract account221 const daiTokenBalance = Number(ethers.utils.formatUnits(await daiToken.balanceOf(addr1.address), 6));222 // Check if the conversion is successful and the user has some dai tokens in their wallet223 log("User USDT Token balance AFTER ETH conversion: ", daiTokenBalance);224 expect(daiTokenBalance).to.be.gt(0);225 // Check that the users ETH balance has reduced regardless of the conversion status226 const ethBalance = Number(ethers.utils.formatEther(await addr1.getBalance()));227 log('User ETH balance AFTER ETH conversion is: ', ethBalance);228 }229 });230 it('Should return USDT and ETH after unwrapping the liquidity nft via univ3', async () => {231 const userSlippageTolerance = config.userSlippageTolerance;232 const zeroAddress = process.env.ZERO_ADDRESS;233 const valuesForUnwrap2 = [234 usdtTokenAddress,235 3000,236 wethAddress]237 const valuesForUnwrap1 = [238 wethAddress,239 3000,240 wethAddress]241 const types = ['address', 'uint24', 'address']242 const encodedKey2 = ethers.utils.defaultAbiCoder.encode(types, valuesForUnwrap2)243 const incentiveId2 = ethers.utils.keccak256(encodedKey2)244 console.log(incentiveId2);245 const encodedKey1 = ethers.utils.defaultAbiCoder.encode(types, valuesForUnwrap1)246 const incentiveId1 = ethers.utils.keccak256(encodedKey1)247 await hre.network.provider.send("hardhat_setBalance", [wrapper.address, "0xDE0B6B3A7640000",]);248 const amountPlaceholder = ethers.utils.parseEther(unitAmount)249 const deadline = Math.floor(new Date().getTime() / 1000) + 1000;250 const positionManager_contract = new ethers.Contract(251 addr.swaps.positionManager.mainnet,252 abi_position_manager,253 provider254 );255 let unwrapParams = {256 tokenId: 134216,257 destinationToken: zeroAddress,258 paths: [incentiveId1, "0xdac17f958d2ee523a2206206994597c13d831ec7000bb8c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"],259 amount: amountPlaceholder,260 userSlippageTolerance: userSlippageTolerance,261 deadline: deadline,262 };263 await positionManager_contract.connect(addr1).approve(wrapper.address, 134216);264 const { status1 } = await (await wrapper.connect(addr1).unwrap(unwrapParams)).wait();265 // Check that the users ETH balance has reduced regardless of the conversion status266 const ethBalance = Number(ethers.utils.formatEther(await addr1.getBalance()));267 log('User ETH balance AFTER unwraping to ETH is: ', ethBalance);268 expect(ethBalance).to.be.lt(10001);269 });270 });...

Full Screen

Full Screen

mjsonwp.js

Source:mjsonwp.js Github

copy

Full Screen

...173 jsonObj = wrapParams(spec.payloadParams, jsonObj);174 }175 // unwrap params if necessary176 if (spec.payloadParams && spec.payloadParams.unwrap) {177 jsonObj = unwrapParams(spec.payloadParams, jsonObj);178 }179 // ensure that the json payload conforms to the spec180 checkParams(spec.payloadParams, jsonObj);181 // ensure the session the user is trying to use is valid182 // turn the command and json payload into an argument list for183 // the driver methods184 let args = makeArgs(req.params, jsonObj, spec.payloadParams || []);185 let driverRes;186 // validate command args according to MJSONWP187 if (validators[spec.command]) {188 validators[spec.command](...args);189 }190 // run the driver command wrapped inside the argument validators191 log.info(`Calling ${driver.constructor.name}.${spec.command}() with args: ` +...

Full Screen

Full Screen

base.classes.test.js

Source:base.classes.test.js Github

copy

Full Screen

1import {assert} from 'chai';2import td from 'testdouble';3import bel from 'bel';4import {DisposableViewModel,5 PlainViewModel,6 ComponentViewModel,7 HookableComponentViewModel} from '../../src/mdc-knockout-base';8import ko from 'knockout';9suite('base classes');10test('base exports DisposableViewModel, PlainViewModel, and ComponentViewModel', () => {11 assert.isFunction(DisposableViewModel);12 assert.isFunction(PlainViewModel);13 assert.isFunction(ComponentViewModel);14});15test('DisposableViewModel has a method "dispose"', () => {16 const vm = new DisposableViewModel();17 assert.isFunction(vm.dispose);18});19test('DisposableViewModel has a property-setter "track"', () => {20 const vm = new DisposableViewModel();21 assert.property(vm, 'track');22 assert.isUndefined(vm.track);23});24test('DisposableViewModel disposes all tracked observables', () => {25 const vm = new DisposableViewModel();26 const disposeObservable = td.function();27 vm.track = {dispose: disposeObservable};28 vm.dispose();29 td.verify(disposeObservable());30});31test('PlainViewModel extends DisposableViewModel', () => {32 const vm = new PlainViewModel();33 assert.instanceOf(vm, DisposableViewModel);34});35test('PlainViewModel instance has "root", "bindings", and "attrs" properties', () => {36 const vm = new PlainViewModel();37 assert.property(vm, 'root');38 assert.property(vm, 'bindings');39 assert.property(vm, 'attrs');40});41test('PlainViewModel has "defaultParams", "unwrapParams", and "forceBindings" property-getters', () => {42 const vm = new PlainViewModel();43 assert.property(vm, 'defaultParams');44 assert.deepEqual(vm.defaultParams, {});45 assert.property(vm, 'unwrapParams');46 assert.deepEqual(vm.unwrapParams, []);47 assert.property(vm, 'forceBindings');48 assert.deepEqual(vm.forceBindings, {});49});50test('PlainViewModel has "extend" method', () => {51 const vm = new PlainViewModel();52 assert.isFunction(vm.extend);53});54test('PlainViewModel constructor calls extend method', () => {55 const extender = td.function();56 class TestVM extends PlainViewModel {57 constructor () {58 super();59 }60 extend () {61 extender();62 }63 }64 const vm = new TestVM();65 td.verify(extender());66});67test('PlainViewModel constructor assigns "root" and "attrs" arguments to corresponding instance properties', () => {68 const vm = new PlainViewModel('root', null, 'attrs');69 assert.strictEqual(vm.root, 'root');70 assert.strictEqual(vm.attrs, 'attrs');71});72test('PlainViewModel constructor assigns "params" argument to "bindings" instance property ' +73 'when "defaultParams", "unwrapParams", and "forceBindings" have default values', () => {74 const params = {75 a: 1,76 b: 'b',77 c: () => {}78 };79 const vm = new PlainViewModel('', params, '');80 assert.strictEqual(vm.bindings, params);81});82test('PlainViewModel constructor adds bindings based on "forceBindings" value', () => {83 class TestVM extends PlainViewModel {84 get forceBindings () {85 return {86 a: () => 1,87 b: () => 2,88 }89 }90 }91 const vm = new TestVM('', {});92 assert.property(vm.bindings, 'a');93 assert.property(vm.bindings, 'b');94 assert.strictEqual(vm.bindings.a, 1);95 assert.strictEqual(vm.bindings.b, 2);96});97test('PlainViewModel constructor does not force bindings if they are already present', () => {98 class TestVM extends PlainViewModel {99 get forceBindings () {100 return {101 a: () => 1,102 b: () => 2,103 }104 }105 }106 const vm = new TestVM('', {a: 3});107 assert.property(vm.bindings, 'a');108 assert.property(vm.bindings, 'b');109 assert.strictEqual(vm.bindings.a, 3);110 assert.strictEqual(vm.bindings.b, 2);111});112test('PlainViewModel constructor adds properties to instance based on "defaultParams" value', () => {113 const observable = ko.observable();114 class TestVM extends PlainViewModel {115 get defaultParams () {116 return {117 a: '',118 b: 1,119 c: observable120 }121 }122 }123 const vm = new TestVM('', {});124 assert.property(vm, 'a');125 assert.property(vm, 'b');126 assert.property(vm, 'c');127 assert.strictEqual(vm.a, '');128 assert.strictEqual(vm.b, 1);129 assert.equal(vm.c, observable);130});131test('PlainViewModel constructor overwrites default param value when it is present in "params" argument', () => {132 class TestVM extends PlainViewModel {133 get defaultParams () {134 return {135 a: '',136 b: 2137 }138 }139 }140 const vm = new TestVM('', {a: 1, c:3});141 assert.property(vm, 'a');142 assert.property(vm, 'b');143 assert.property(vm.bindings, 'c');144 assert.strictEqual(vm.a, 1);145 assert.strictEqual(vm.b, 2);146 assert.strictEqual(vm.bindings.c, 3);147});148test('PlainViewModel constructor converts properties to non-observables based on "unwrapParams" value', () => {149 const observableA = ko.observable(1);150 const computed = ko.computed(() => observableA() + 1);151 const wrapped = ko.observable(observableA);152 class TestVM extends PlainViewModel {153 get defaultParams () {154 return {155 a: observableA,156 computed: computed,157 wrapped: wrapped,158 b: 3159 }160 }161 get unwrapParams () {162 return ['a', 'computed', 'wrapped', 'b']163 }164 }165 const vm = new TestVM('', {});166 assert.property(vm, 'a');167 assert.property(vm, 'computed');168 assert.property(vm, 'wrapped');169 assert.property(vm, 'b');170 assert.strictEqual(vm.a, 1);171 assert.strictEqual(vm.computed, 2);172 assert.strictEqual(vm.wrapped, 1);173 assert.strictEqual(vm.b, 3);174});175test('ComponentViewModel extends PlainViewModel', () => {176 const vm = new ComponentViewModel();177 assert.instanceOf(vm, PlainViewModel);178});179test('ComponentViewModel constructor assigns "MDCComponent" argument ' +180 'to corresponding instance properties', () => {181 const vm = new ComponentViewModel(null, null, null, 'MDCComponent');182 assert.strictEqual(vm.MDCComponent, 'MDCComponent');183});184test('ComponentViewModel instance has "instance" property and "initialize" method', () => {185 const vm = new ComponentViewModel();186 assert.strictEqual(vm.instance, null);187 assert.isFunction(vm.initialize);188});189test('ComponentViewModel instance destroys its "instance" property on disposal', () => {190 const vm = new ComponentViewModel();191 const destroy = td.function();192 vm.instance = {destroy: destroy};193 vm.dispose();194 td.verify(destroy());195});196test('HookableComponentViewModel extends ComponentViewModel', () => {197 const vm = new HookableComponentViewModel();198 assert.instanceOf(vm, ComponentViewModel);199});200test('HookableComponentViewModel has stub property-getters "hookedElement" and "hookedProperties"', () => {201 const vm = new HookableComponentViewModel();202 const getHookedElement = () => vm.hookedElement;203 const getHookedProperties = () => vm.hookedProperties;204 assert.isOk('hookedElement' in vm);205 assert.isOk('hookedProperties' in vm);206 assert.throws(getHookedElement);207 assert.throws(getHookedProperties);208});209test('HookableComponentViewModel installs hooks on initialization', () => {210 const hook = td.function();211 const element = bel`<input>`;212 class TestClass extends HookableComponentViewModel {213 get hookedElement () {214 return element;215 }216 get hookedProperties () {217 return {disabled: hook}218 }219 }220 const vm = new TestClass(null, null, null, 'MDCComponentStub');221 vm.initialize();222 element.disabled = true;223 td.verify(hook(true));224});225test('HookableComponentViewModel does not require extending classes to use "super()" ' +226 'inside "initialize" method', () => {227 const hook = td.function();228 const init = td.function();229 const element = bel`<input>`;230 class TestClass extends HookableComponentViewModel {231 initialize () {232 init();233 }234 get hookedElement () {235 return element;236 }237 get hookedProperties () {238 return {disabled: hook}239 }240 }241 const vm = new TestClass(null, null, null, 'MDCComponentStub');242 vm.initialize();243 td.verify(init());244 element.disabled = true;245 td.verify(hook(true));246});247test('HookableComponentViewModel uninstalls hooks on disposal', () => {248 const hook = td.function();249 const element = bel`<input>`;250 class TestClass extends HookableComponentViewModel {251 get hookedElement () {252 return element253 }254 get hookedProperties () {255 return {disabled: hook}256 }257 }258 const vm = new TestClass(null, null, null, 'MDCComponentStub');259 vm.initialize();260 element.disabled = true;261 vm.dispose();262 element.disabled = false;263 td.verify(hook(td.matchers.anything()), {times: 1});...

Full Screen

Full Screen

mdc-knockout-base.js

Source:mdc-knockout-base.js Github

copy

Full Screen

1import {toJS, isSubscribable} from './util.js';2class DisposableViewModel {3 constructor () {4 this.subscriptions_ = [];5 }6 /***7 Keep track of the external dependencies.8 Use for every ko.computed or subscription created inside a ViewModel:9 Usage:10 this.track = someObservable.subscribe( () => void );11 or:12 this.track = ko.computed( () => someObservable1() + someObservable2() )13 Note: ko.pureComputed do not require any tracking14 */15 set track (subscription) {16 this.subscriptions_.push(subscription);17 }18 dispose () {19 this.subscriptions_.forEach(item => item.dispose());20 }21}22class PlainViewModel extends DisposableViewModel {23 randomPrefixed (prefix) {24 return prefix + '-' + Math.floor(Math.random() * 1000000)25 }26 constructor (root, params, attrs) {27 super();28 this.root = root;29 this.attrs = attrs;30 const defaultParams = this.defaultParams;31 Object.keys(defaultParams).forEach( name => {32 const defaultValue = defaultParams[name];33 if (params.hasOwnProperty(name)) {34 this[name] = params[name];35 delete params[name];36 }37 else {38 this[name] = defaultValue;39 }40 });41 this.unwrapParams.forEach(name => {42 if (isSubscribable(this[name])) {43 this[name] = toJS(this[name]);44 }45 });46 const forced = this.forceBindings;47 if (params) {48 Object.keys(forced).forEach(name => {49 if (!(name in params)){50 params[name] = forced[name]();51 }52 });53 }54 this.bindings = params;55 this.extend();56 }57 extend () {58 }59 get forceBindings () {60 // e.g return {'disable': () => this.disableOnInit}61 return {}62 }63 get defaultParams () {64 // e.g return {text: 'default'}65 return {}66 }67 get unwrapParams () {68 // e.g return ['fullwidth']69 return []70 }71}72class ComponentViewModel extends PlainViewModel {73 constructor (root, params, attrs, MDCComponent) {74 super(root, params, attrs);75 this.MDCComponent = MDCComponent;76 this.instance = null;77 }78 initialize (parent) {79 }80 dispose () {81 super.dispose();82 this.instance && this.instance.destroy();83 }84}85class HookableComponentViewModel extends ComponentViewModel {86 constructor (...args) {87 super(...args);88 this.hooked_ = [];89 // don't have to use super() in the extending class method90 let init = this.initialize.bind(this);91 this.initialize = parent => {92 init(parent);93 this.installHooks_();94 }95 }96 get hookedElement () {97 // e.g return this.root.querySelector('input')98 throw new Error('Define "hookedElement" property in your class')99 }100 get hookedProperties () {101 // e.g return {'disabled': state => console.log(state)}102 throw new Error('Define "hookedProperties" property in your class')103 }104 installHooks_ () {105 const element = this.hookedElement;106 const elementProto = Object.getPrototypeOf(element);107 Object.keys(this.hookedProperties).forEach(propertyName => {108 let desc = Object.getOwnPropertyDescriptor(element, propertyName);109 if (!desc) {110 desc = Object.getOwnPropertyDescriptor(elementProto, propertyName);111 }112 // We have to check for this descriptor, since some browsers (Safari) don't support its return.113 // See: https://bugs.webkit.org/show_bug.cgi?id=49739114 if (validDescriptor(desc)) {115 this.hooked_.push({element: element, propertyName: propertyName, descriptor: desc});116 Object.defineProperty(element, propertyName, {117 get: desc.get,118 set: state => {119 desc.set.call(element, state);120 this.hookedProperties[propertyName](state);121 },122 configurable: desc.configurable,123 enumerable: desc.enumerable,124 });125 }126 });127 }128 uninstallHooks_ () {129 this.hooked_.forEach(item => {130 Object.defineProperty(item.element, item.propertyName, item.descriptor);131 });132 }133 dispose () {134 this.uninstallHooks_();135 super.dispose();136 }137}138function validDescriptor(elementPropDesc) {139 return elementPropDesc && typeof elementPropDesc.set === 'function';140}...

Full Screen

Full Screen

mdc-knockout-toolbar.js

Source:mdc-knockout-toolbar.js Github

copy

Full Screen

1import {ComponentViewModel} from './mdc-knockout-base';2import ToolbarTemplate from './templates/toolbar.html';3import {isSubscribable} from './util';4class ToolbarViewModel extends ComponentViewModel {5 extend () {6 if (this.waterfall) {7 this.fixed = true;8 }9 10 if (this.lastrow) {11 this.fixed = true;12 }13 }14 initialize () {15 if (this.adjust) {16 this.instance.fixedAdjustElement = this.adjust;17 }18 if (this.flexible && isSubscribable(this.ratio)) {19 this.instance.listen('MDCToolbar:change', (evt) => {20 this.ratio(evt.detail.flexibleExpansionRatio);21 });22 }23 }24 get sectionOnlyAttributes_ () {25 return ['start', 'end', 'shrink'];26 }27 createTitleNode_ (text) {28 const span = document.createElement('span');29 span.setAttribute('title', true);30 span.textContent = text;31 return span;32 }33 wrapTextNodes_ (nodes) {34 nodes.forEach(node => {35 [...node.childNodes].forEach(child => {36 if (child.nodeType == 3 && child.textContent.match(/[^\s]/)) {37 const text = child.textContent;38 const titleNode = this.createTitleNode_(text);39 node.replaceChild(titleNode, child);40 }41 });42 });43 }44 listChildren_ (parents) {45 let children = [];46 parents.forEach(parent => {47 if (parent.children.length) {48 children = children.concat([...parent.children]);49 }50 });51 return children;52 }53 wrapAsSections_ (nodes) {54 const result = [];55 nodes.forEach(node => {56 let wrapIt = false;57 if (node.tagName && node.tagName == 'SECTION') {58 result.push(node);59 }60 else {61 const wrapped = document.createElement('SECTION');62 const parent = node.parentNode;63 parent.replaceChild(wrapped, node);64 wrapped.appendChild(node);65 result.push(wrapped);66 [...node.attributes].forEach(attr => {67 if (this.sectionOnlyAttributes_.indexOf(attr.name) !== -1) {68 node.removeAttributeNode(attr);69 wrapped.setAttributeNode(attr);70 }71 });72 }73 });74 return result;75 }76 combineNonDivs_ (nodes) {77 const result = [];78 let group = [];79 nodes.forEach((node, i) => {80 const isDiv = (node.nodeType == 1 && node.tagName == 'DIV');81 const isEmptyText = (node.nodeType == 3 && !node.textContent.match(/[^\s]/));82 if (!isDiv && !isEmptyText) {83 group.push(node);84 }85 if (isDiv || (i == nodes.length - 1)) {86 if (group.length) {87 const div = document.createElement('div');88 group.forEach(element => div.appendChild(element));89 result.push(div);90 group = [];91 }92 }93 if (isDiv) {94 result.push(node);95 }96 });97 return result;98 }99 childrenTransform (children) {100 const divs = this.combineNonDivs_(children);101 this.wrapTextNodes_(divs);102 if (!divs.length) {103 divs.push(document.createElement('div'));104 }105 const divChildren = this.listChildren_(divs);106 const sections = this.wrapAsSections_(divChildren);107 this.wrapTextNodes_(sections);108 return divs;109 }110 get defaultParams () {111 return {112 fixed: false,113 waterfall: false,114 lastrow: false,115 flexible: false,116 adjust: undefined,117 ratio: null118 }119 }120 get unwrapParams () {121 return ['fixed', 'waterfall', 'lastrow', 'flexible', 'adjust'];122 }123}...

Full Screen

Full Screen

mdc-knockout-textfield.js

Source:mdc-knockout-textfield.js Github

copy

Full Screen

1import {ComponentViewModel} from './mdc-knockout-base';2import TextfieldTemplate from './templates/textfield.html';3class TextfieldViewModel extends ComponentViewModel {4 extend () {5 if (!this.attrs['id']) {6 this.attrs['id'] = this.randomPrefixed('textfield-auto-id');7 }8 this.attrs['aria-controls'] = this.randomPrefixed('textfield-helptext');9 if (this.fullwidth && this.label) {10 this.attrs['aria-label'] = this.label;11 this.attrs['placeholder'] = this.label;12 }13 }14 get labelElement_ () {15 return this.root.querySelector('label');16 }17 get textElement_ () {18 return this.root.querySelector('input') || this.root.querySelector('textarea');19 }20 initialize () {21 if (this.fullwidth && !this.label) {22 const labelText = this.labelElement_.textContent;23 this.textElement_.setAttribute('aria-label', labelText);24 this.textElement_.setAttribute('placeholder', labelText);25 }26 }27 childrenTransform (children) {28 const result = [];29 children.forEach(child => {30 if (child.nodeType == 1 && child.tagName == 'P') {31 child.setAttribute('aria-hidden', true);32 child.setAttribute('id', this.attrs['aria-controls']);33 result.push(child);34 }35 });36 return result;37 }38 get forceBindings () {39 return {40 disable: () => ('disabled' in this.attrs)41 }42 }43 get defaultParams () {44 return {45 label: '',46 invalid: false,47 multiline: false,48 fullwidth: false,49 box: false50 }51 }52 get unwrapParams () {53 return ['multiline', 'fullwidth', 'invalid', 'box']54 }55}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unwrapParams, wrapParams } = require('appium-base-driver').protocol;2class AppiumDriver {3 constructor () {4 this.unwrapParams = unwrapParams;5 this.wrapParams = wrapParams;6 }7}8module.exports = AppiumDriver;9const unwrap = require('appium-base-driver').protocol.unwrap;10function unwrapParams (driver, fn, args) {11 return unwrap(args, driver);12}13function wrapParams (driver, fn, res, sessionId) {14 return res;15}16module.exports = {17};18function unwrap (args, driver) {19 if (args && Array.isArray(args)) {20 return args.map((arg) => unwrap(arg, driver));21 } else if (_.isObject(args)) {22 return _.mapValues(args, (arg) => unwrap(arg, driver));23 } else if (_.isString(args)) {24 return driver.replaceValuePattern(args);25 } else {26 return args;27 }28}

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumBaseDriver = require('appium-base-driver');2const params = AppiumBaseDriver.unwrapParams({caps: {platformName: 'android'}});3console.log(params);4const AppiumBaseDriver = require('appium-base-driver');5const params = AppiumBaseDriver.unwrapParams({platformName: 'android'});6console.log(params);7{8 caps: { platformName: 'android' },

Full Screen

Using AI Code Generation

copy

Full Screen

1var BaseDriver = require('appium-base-driver').BaseDriver;2var b = new BaseDriver();3var params = b.unwrapParams({foo: 'bar'});4console.log(params);5Expected: {foo: 'bar'}6Actual: {foo: 'bar'}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { unwrapParams } from 'appium-base-driver'2var params = unwrapParams(args);3import { unwrapElement } from 'appium-base-driver'4var element = unwrapElement(args);5import { unwrapElement } from 'appium-base-driver'6var element = unwrapElement(args);7import { unwrapExpectedConditions } from 'appium-base-driver'8var element = unwrapExpectedConditions(args);9import { unwrapExpectedConditions } from 'appium-base-driver'10var element = unwrapExpectedConditions(args);11import { unwrapExpectedConditions } from 'appium-base-driver'12var element = unwrapExpectedConditions(args);13import { unwrapExpectedConditions } from 'appium-base-driver'14var element = unwrapExpectedConditions(args);15import { unwrapExpectedConditions } from 'appium-base-driver'16var element = unwrapExpectedConditions(args);17import { unwrapExpectedConditions } from 'appium-base-driver'18var element = unwrapExpectedConditions(args);19import { unwrapExpectedConditions } from 'appium-base-driver'20var element = unwrapExpectedConditions(args);21import { unwrapExpectedConditions } from 'appium-base-driver'22var element = unwrapExpectedConditions(args);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unwrapParams } = require('appium-base-driver');2const params = await unwrapParams(req.body);3console.log(params);4const { unwrapElement } = require('appium-base-driver');5const element = await unwrapElement(params.elementId);6console.log(element);7const { unwrapElements } = require('appium-base-driver');8const elements = await unwrapElements(params.elementId);9console.log(elements);10const { unwrapElementFromParams } = require('appium-base-driver');11const element = await unwrapElementFromParams(params);12console.log(element);13const { unwrapElementsFromParams } = require('appium-base-driver');14const elements = await unwrapElementsFromParams(params);15console.log(elements);16const { unwrapElementFromParams } = require('appium-base-driver');17const element = await unwrapElementFromParams(params);18console.log(element);19const { unwrapElementsFromParams } = require('appium-base-driver');20const elements = await unwrapElementsFromParams(params);21console.log(elements);22const { unwrapElementFromParams } = require('appium-base-driver');23const element = await unwrapElementFromParams(params);24console.log(element);25const { unwrapElementsFromParams } = require('appium-base-driver');26const elements = await unwrapElementsFromParams(params);27console.log(elements);28const { unwrapElementFromParams } = require('appium-base-driver');29const element = await unwrapElementFromParams(params);30console.log(element);31const { unwrapElementsFromParams } = require('appium-base-driver');32const elements = await unwrapElementsFromParams(params);33console.log(elements);34const { unwrapElementFromParams } = require('appium-base-driver

Full Screen

Using AI Code Generation

copy

Full Screen

1const { unwrapParams } = require('appium-base-driver').androidHelpers;2const params = { 'elementId': '1', 'text': 'some text', 'id': 'someId' };3const unwrappedParams = unwrapParams(params);4console.log(unwrappedParams);5{6}7const { unwrapElement } = require('appium-base-driver').androidHelpers;8const params = { 'elementId': '1', 'text': 'some text', 'id': 'someId' };9const unwrappedParams = unwrapElement(params);10console.log(unwrappedParams);11{12}13const { unwrapElementFromParams } = require('appium-base-driver').androidHelpers;14const params = { 'elementId': '1', 'text': 'some text', 'id': 'someId' };15const unwrappedParams = unwrapElementFromParams(params);16console.log(unwrappedParams);17{18}19const { unwrapEl } = require('appium-base-driver').androidHelpers;20const params = { 'elementId': '1', 'text': 'some text', 'id': 'someId' };21const unwrappedParams = unwrapEl(params);22console.log(unwrappedParams);23{24}25const { unwrapElements } = require('appium-base-driver').androidHelpers;26const params = { 'elementId': '1', 'text': 'some text', 'id': 'someId' };27const unwrappedParams = unwrapElements(params);28console.log(unwrappedParams);29{30}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful