Best JavaScript code snippet using navalia
cdps.js
Source:cdps.js
1import produce from 'immer';2import round from 'lodash/round';3import { multiply, divide, subtract } from 'utils/bignumber';4import { getIlkData } from './feeds';5import { ETH, MDAI } from '@makerdao/dai-plugin-mcd';6import { fromWei } from 'utils/units';7export const INK = 'ink';8export const ART = 'art';9export const initialState = {};10const defaultCdpState = {11 inited: false,12 [INK]: '',13 [ART]: '',14 ilk: ''15};16export function getCdp(cdpId, { cdps, feeds }) {17 cdpId = cdpId.toString();18 if (!cdps[cdpId]) return defaultCdpState;19 else20 return {21 id: cdpId,22 ...cdps[cdpId],23 ...getIlkData(feeds, cdps[cdpId].ilk)24 };25}26export function getDebtAmount(cdp, rounded = true, precision = 2) {27 if (!cdp.art || !cdp.rate) return '';28 return rounded29 ? round(multiply(cdp.art, cdp.rate), precision)30 : multiply(cdp.art, cdp.rate);31}32export function getLiquidationPrice(cdp, rounded = true, precision = 2) {33 if (!cdp.liquidationRatio || !cdp.ink) return '';34 const debtAmount = getDebtAmount(cdp, false);35 if (!debtAmount) return '';36 if (!parseFloat(cdp.ink)) return Infinity;37 const val = divide(multiply(debtAmount, cdp.liquidationRatio / 100), cdp.ink);38 return rounded ? round(val, precision) : val;39}40export function getCollateralPrice(cdp, rounded = true, precision = 2) {41 if (!cdp.price) return '';42 return rounded43 ? round(cdp.price.toNumber(), precision)44 : cdp.price.toNumber();45}46export function getCollateralAmount(cdp, rounded = true, precision = 2) {47 if (!cdp.ink) return '';48 return rounded ? round(cdp.ink, precision) : cdp.ink;49}50export function getCollateralValueUSD(cdp, rounded = true, precision = 2) {51 if (!cdp.ink) return '';52 const collateralPrice = getCollateralPrice(cdp, false);53 if (!collateralPrice) return;54 return rounded55 ? round(multiply(cdp.ink, collateralPrice), precision)56 : multiply(cdp.ink, collateralPrice);57}58export function getCollateralizationRatio(cdp, rounded = true, precision = 2) {59 const collateralValueUSD = getCollateralValueUSD(cdp, false);60 if (!collateralValueUSD) return '';61 const debtAmount = getDebtAmount(cdp, false);62 if (!parseFloat(debtAmount)) return Infinity;63 return rounded64 ? round(multiply(divide(collateralValueUSD, debtAmount), 100), precision)65 : multiply(divide(collateralValueUSD, debtAmount), 100);66}67export function getMinCollateralNeeded(cdp, rounded = true, precision = 2) {68 if (!cdp.liquidationRatio) return '';69 const debtAmount = getDebtAmount(cdp, false);70 if (!debtAmount) return '';71 const collateralPrice = getCollateralPrice(cdp, false);72 if (!collateralPrice) return '';73 return rounded74 ? round(75 divide(76 multiply(debtAmount, divide(cdp.liquidationRatio, 100)),77 collateralPrice78 ),79 precision80 )81 : divide(82 multiply(debtAmount, divide(cdp.liquidationRatio, 100)),83 collateralPrice84 );85}86export function getCollateralAvailableAmount(87 cdp,88 rounded = true,89 precision = 290) {91 const collateralAmount = getCollateralAmount(cdp, false);92 if (!collateralAmount) return '';93 const minCollateralNeeded = getMinCollateralNeeded(cdp, false);94 if (!minCollateralNeeded) return '';95 const collateralAvailableAmount = subtract(96 collateralAmount,97 minCollateralNeeded98 );99 return rounded100 ? round(101 collateralAvailableAmount < 0 ? 0 : collateralAvailableAmount,102 precision103 )104 : collateralAvailableAmount < 0105 ? 0106 : collateralAvailableAmount;107}108export function getCollateralAvailableValue(109 cdp,110 rounded = true,111 precision = 2112) {113 const collateralAvailableAmount = getCollateralAvailableAmount(cdp, false);114 if (!collateralAvailableAmount) return '';115 const collateralPrice = getCollateralPrice(cdp, false);116 if (!collateralPrice) return;117 return rounded118 ? round(multiply(collateralAvailableAmount, collateralPrice), precision)119 : multiply(collateralAvailableAmount, collateralPrice);120}121export function getDaiAvailable(cdp, rounded = true, precision = 2) {122 if (!cdp.liquidationRatio) return '';123 const collateralValueUSD = getCollateralValueUSD(cdp, false);124 if (!collateralValueUSD) return '';125 const debtAmount = getDebtAmount(cdp, false);126 if (!debtAmount) return '';127 return rounded128 ? round(129 subtract(130 divide(collateralValueUSD, cdp.liquidationRatio / 100),131 debtAmount132 ),133 precision134 )135 : subtract(136 divide(collateralValueUSD, cdp.liquidationRatio / 100),137 debtAmount138 );139}140export function getEventHistory(cdp) {141 // eslint-disable-line no-unused-vars142 //return cdp.getEventHistory();143 return mockHistoryDataFromSDK; //TODO switch to real data144}145export const mockHistoryDataFromSDK = [146 {147 transactionHash:148 '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f',149 changeInCollateral: ETH(99.5),150 collateralAction: 'free',151 time: new Date(Date.now()),152 senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a',153 resultingCollateral: ETH(900.5),154 resultingDebt: MDAI(10090),155 ilk: 'ETH-A'156 },157 {158 transactionHash:159 '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f',160 changeInCollateral: ETH(0),161 changeInDai: MDAI(1000),162 daiAction: 'wipe',163 time: new Date(Date.now() - 10000000000),164 senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a',165 resultingCollateral: ETH(1000),166 resultingDebt: MDAI(10045),167 ilk: 'ETH-A'168 },169 {170 transactionHash:171 '0xbe023a205453b833e65bf29063de8b8b3bd44d2e68c9c079f681ec46a765a63f',172 changeInCollateral: ETH(10000),173 collateralAction: 'lock',174 changeInDai: MDAI(120000),175 daiAction: 'draw',176 time: new Date(Date.now() - 20000000000),177 senderAddress: '0x1ad35418e7b7c5746ea42295a1100480a810256a',178 resultingCollateral: ETH(1000),179 resultingDebt: MDAI(1100),180 ilk: 'ETH-A'181 }182];183function convert(valueType, value) {184 switch (valueType) {185 case INK:186 case ART:187 return fromWei(value);188 default:189 return value;190 }191}192const reducer = produce((draft, { type, value }) => {193 if (!type) return;194 const [label, cdpId, valueType] = type.split('.');195 if (label === 'cdp') {196 if (draft[cdpId]) draft[cdpId][valueType] = convert(valueType, value);197 else198 draft[cdpId] = {199 ...defaultCdpState,200 inited: true,201 [valueType]: convert(valueType, value)202 };203 }204}, initialState);...
Presentation.js
Source:Presentation.js
1import React, { useState } from 'react';2import lang from 'languages';3import { TextBlock } from 'components/Typography';4import PageContentLayout from 'layouts/PageContentLayout';5import {6 getDebtAmount,7 getLiquidationPrice,8 getCollateralPrice,9 getCollateralAmount,10 getCollateralValueUSD,11 getCollateralizationRatio,12 getCollateralAvailableAmount,13 getCollateralAvailableValue,14 getDaiAvailable,15 getEventHistory16} from 'reducers/cdps';17import { Box, Grid, Flex, Text } from '@makerdao/ui-components-core';18import History from './History';19import {20 ActionButton,21 ActionContainerRow,22 AmountDisplay,23 CdpViewCard,24 ExtraInfo,25 InfoContainerRow26} from './subcomponents';27import theme from '../../styles/theme';28import FullScreenAction from './FullScreenAction';29export default function({ cdp, showSidebar, account, network }) {30 const cdpId = parseInt(cdp.id);31 console.log(`rendering cdp ${cdpId}`);32 const gem = cdp.currency.symbol;33 const debtAmount = getDebtAmount(cdp);34 let liquidationPrice = getLiquidationPrice(cdp);35 if (liquidationPrice) liquidationPrice = liquidationPrice.toFixed(2);36 if (liquidationPrice === 'Infinity')37 liquidationPrice = lang.cdp_page.not_applicable;38 const collateralPrice = getCollateralPrice(cdp);39 const collateralAmount = getCollateralAmount(cdp);40 const collateralUSDValue = getCollateralValueUSD(cdp);41 let collateralizationRatio = getCollateralizationRatio(cdp);42 if (collateralizationRatio === Infinity)43 collateralizationRatio = lang.cdp_page.not_applicable;44 const collateralAvailableAmount = getCollateralAvailableAmount(cdp);45 const collateralAvailableValue = getCollateralAvailableValue(cdp);46 const daiAvailable = getDaiAvailable(cdp);47 const eventHistory = getEventHistory(cdp);48 const isOwner = account && account.cdps.some(userCdp => userCdp.id === cdpId);49 const [actionShown, setActionShown] = useState(null);50 const showAction = props => {51 const emSize = parseInt(getComputedStyle(document.body).fontSize);52 const pxBreakpoint = parseInt(theme.breakpoints.l) * emSize;53 const isMobile = document.documentElement.clientWidth < pxBreakpoint;54 if (isMobile) {55 setActionShown(props);56 } else {57 showSidebar(props);58 }59 };60 return (61 <PageContentLayout>62 <Box>63 <Text.h2>64 {lang.cdp} {cdpId}65 </Text.h2>66 </Box>67 <Grid68 py="m"69 gridColumnGap="l"70 gridTemplateColumns={['1fr', '1fr', '1fr 1fr']}71 >72 <CdpViewCard title={lang.cdp_page.liquidation_price}>73 <Flex alignItems="flex-end" mt="s" mb="xs">74 <AmountDisplay amount={liquidationPrice} denomination="USD" />75 <ExtraInfo>({gem}/USD)</ExtraInfo>76 </Flex>77 <InfoContainerRow78 title={79 <TextBlock fontSize="l">80 {lang.cdp_page.current_price_info}81 <ExtraInfo ml="2xs">{`(${gem}/USD)`}</ExtraInfo>82 </TextBlock>83 }84 value={`${collateralPrice} USD`}85 />86 <InfoContainerRow87 title={lang.cdp_page.liquidation_penalty}88 value={cdp.liquidationPenalty + '%'}89 />90 </CdpViewCard>91 <CdpViewCard title={lang.cdp_page.collateralization_ratio}>92 <Flex alignItems="flex-end" mt="s" mb="xs">93 <AmountDisplay amount={collateralizationRatio} denomination="%" />94 </Flex>95 <InfoContainerRow96 title={lang.cdp_page.minimum_ratio}97 value={cdp.liquidationRatio + '.00%'}98 />99 <InfoContainerRow100 title={lang.cdp_page.stability_fee}101 value={cdp.stabilityFee + '%'}102 />103 </CdpViewCard>104 <CdpViewCard title={`${gem} ${lang.cdp_page.locked.toLowerCase()}`}>105 <ActionContainerRow106 title={`${gem} ${lang.cdp_page.locked.toLowerCase()}`}107 value={`${collateralAmount} ${gem}`}108 conversion={`${collateralUSDValue} USD`}109 button={110 <ActionButton111 disabled={!account}112 onClick={() =>113 showAction({ type: 'deposit', props: { cdpId } })114 }115 >116 {lang.actions.deposit}117 </ActionButton>118 }119 />120 <ActionContainerRow121 title={lang.cdp_page.able_withdraw}122 value={`${collateralAvailableAmount} ${gem}`}123 conversion={`${collateralAvailableValue} USD`}124 button={125 <ActionButton126 disabled={!account || !isOwner}127 onClick={() =>128 showAction({ type: 'withdraw', props: { cdpId } })129 }130 >131 {lang.actions.withdraw}132 </ActionButton>133 }134 />135 </CdpViewCard>136 <CdpViewCard title={`DAI ${lang.cdp_page.position}`}>137 <ActionContainerRow138 title={lang.cdp_page.outstanding_dai_debt}139 value={debtAmount + ' DAI'}140 button={141 <ActionButton142 disabled={!account}143 onClick={() =>144 showAction({ type: 'payback', props: { cdpId } })145 }146 >147 {lang.actions.pay_back}148 </ActionButton>149 }150 />151 <ActionContainerRow152 title={lang.cdp_page.available_generate}153 value={`${daiAvailable} DAI`}154 button={155 <ActionButton156 disabled={!account || !isOwner}157 onClick={() =>158 showAction({ type: 'generate', props: { cdpId } })159 }160 >161 {lang.actions.generate}162 </ActionButton>163 }164 />165 </CdpViewCard>166 </Grid>167 <History168 title={lang.cdp_page.tx_history}169 rows={eventHistory}170 network={network}171 />172 {actionShown && (173 <FullScreenAction {...actionShown} reset={() => setActionShown(null)} />174 )}175 </PageContentLayout>176 );...
MulticallService.spec.js
Source:MulticallService.spec.js
1import TestAccountProvider from '@makerdao/test-helpers/src/TestAccountProvider';2import Maker from '../../src/index';3import BigNumber from 'bignumber.js';4import ScdPlugin from '@makerdao/dai-plugin-scd';5import schemas, {6 TOTAL_CDP_DEBT,7 ETH_PRICE,8 CDP_COLLATERAL,9 CDP_DEBT,10 CDP_COLLATERAL_VALUE,11 LAST_CREATED_CDP_COLLATERAL_VALUE,12 CDP_OWNER13} from '../helpers/schemas';14let maker, multicall, watcher, address, cdpId1, cdpId2;15beforeAll(async () => {16 maker = await Maker.create('test', {17 plugins: [[ScdPlugin, { network: 'testnet' }]],18 web3: {19 pollingInterval: 10020 },21 multicall: {22 debounceTime: 123 }24 });25 await maker.authenticate();26 address = TestAccountProvider.nextAddress();27 multicall = maker.service('multicall');28 watcher = multicall.createWatcher();29 multicall.registerSchemas(schemas);30 // TODO31 const proxyAddress = await maker.service('proxy').ensureProxy();32 const { id: _cdpId1 } = await maker33 .service('cdp')34 .openProxyCdpLockEthAndDrawSai(1, 100, proxyAddress);35 const { id: _cdpId2 } = await maker36 .service('cdp')37 .openProxyCdpLockEthAndDrawSai(5, 100, proxyAddress);38 await maker.service('cdp').openProxyCdpLockEthAndDrawSai(1, 50, proxyAddress);39 cdpId1 = _cdpId1;40 cdpId2 = _cdpId2;41});42beforeEach(() => {43 multicall.start();44});45afterEach(() => {46 multicall.stop();47});48test('get eth balance via multicall', async () => {49 const web3 = multicall.get('web3');50 const fromWei = web3._web3.utils.fromWei;51 watcher.stop();52 const initialBlock = (await web3.getBlock('latest')).number + 1;53 const initialEthBalance = fromWei(await web3.getBalance(address)).toString();54 watcher.tap(() => [55 {56 call: ['getEthBalance(address)(uint256)', address],57 returns: [['ETH_BALANCE', v => fromWei(v.toString())]]58 }59 ]);60 watcher.start();61 const results = {};62 const batchSub = watcher.subscribe(update => (results[update.type] = update.value.toString()));63 const newBlockSub = watcher.onNewBlock(number => (results.blockNumber = number));64 await watcher.awaitInitialFetch();65 batchSub.unsub();66 newBlockSub.unsub();67 expect(results.ETH_BALANCE).toEqual(initialEthBalance);68 expect(parseInt(results.blockNumber)).toEqual(initialBlock);69});70test('base observable', async () => {71 const expectedTotalCdpDebt = BigNumber(250);72 const totalCdpDebt = await maker.latest(TOTAL_CDP_DEBT);73 expect(totalCdpDebt).toEqual(expectedTotalCdpDebt);74});75test('base observable with arg', async () => {76 const expectedCdpCollateral = BigNumber(1);77 const cdpCollateral = await maker.latest(CDP_COLLATERAL, cdpId1);78 expect(cdpCollateral).toEqual(expectedCdpCollateral);79});80test('multiple base observables', async () => {81 const expectedCdpCollateral = BigNumber(1);82 const expectedCdpDebt = BigNumber(100);83 const expectedEthPrice = BigNumber(400);84 const cdpCollateral = await maker.latest(CDP_COLLATERAL, cdpId1);85 const cdpDebt = await maker.latest(CDP_DEBT, cdpId1);86 const ethPrice = await maker.latest(ETH_PRICE);87 expect(cdpCollateral).toEqual(expectedCdpCollateral);88 expect(cdpDebt).toEqual(expectedCdpDebt);89 expect(ethPrice).toEqual(expectedEthPrice);90 expect(multicall.totalActiveSchemas).toEqual(2);91});92test('computed observable', async () => {93 const expectedCdpCollateralValue = BigNumber(400);94 const cdpCollateralValue = await maker.latest(CDP_COLLATERAL_VALUE, cdpId1);95 expect(cdpCollateralValue).toEqual(expectedCdpCollateralValue);96 expect(multicall.totalActiveSchemas).toEqual(2);97});98test('computed observable with nested dependencies', async () => {99 const expectedLastCreatedCdpDebt = BigNumber(400);100 const lastCreatedCdpDebt = await maker.latest(LAST_CREATED_CDP_COLLATERAL_VALUE);101 expect(lastCreatedCdpDebt).toEqual(expectedLastCreatedCdpDebt);102 expect(multicall.totalActiveSchemas).toEqual(3);103});104test('observable throws args validation error', async () => {105 const promise = maker.latest(CDP_COLLATERAL, -9000);106 await expect(promise).rejects.toThrow(/invalid cdp id/i);107});108test('observable throws invalid key error', () => {109 expect(() => {110 maker.latest(null);111 }).toThrow(/invalid observable key/i);112});113test('observable throws no registered schema error', () => {114 expect(() => {115 maker.latest('foo');116 }).toThrow(/no registered schema/i);117});118test('observable throws insufficient args error', async () => {119 const promise = maker.latest(CDP_OWNER);120 await expect(promise).rejects.toThrow(/expects.*argument/i);121});122test('observable throws result validation error', async () => {123 const promise = maker.latest(CDP_COLLATERAL, cdpId2);124 await expect(promise).rejects.toThrow(/Φ/);125});126test('observable throws result validation error 2', async () => {127 const promise = maker.latest(CDP_OWNER, 9000);128 await expect(promise).rejects.toThrow();...
principal.js
Source:principal.js
1/* ======================================================================================2 @author Carlos Doral Pérez (http://webartesanal.com)3 @version 0.194 @copyright Copyright © 2013 Carlos Doral Pérez, All Rights Reserved5 License: GPLv2 or later6 ====================================================================================== */7//8function cdp_cookies_mensaje( texto, clase )9{10 jQuery( '.cdp-cookies-mensajes' ).removeClass( 'error' ).addClass( clase );11 jQuery( '.cdp-cookies-mensajes' ).html( texto ).fadeIn( 500 ).delay( 2000 ).fadeOut( 500 );12}13//14function cdp_cookies_mensaje_error( texto )15{16 cdp_cookies_mensaje( texto, 'error' );17}18//19function guardar()20{21 //22 var datos = {23 action: 'guardar_config',24 texto_aviso: jQuery( '#texto_aviso' ).val(),25 tam_fuente: jQuery( '#tam_fuente' ).val(),26 layout: jQuery( '#layout' ).val(),27 posicion: jQuery( '#posicion' ).val(),28 alineacion: jQuery( '#alineacion' ).val(),29 tema: jQuery( '#tema:checked' ).val(),30 enlace_politica: jQuery( '#enlace_politica' ).val(),31 enlace_mas_informacion: jQuery( '#enlace_mas_informacion' ).val(),32 nonce_guardar: cdp_cookies_info.nonce_guardar,33 comportamiento: jQuery( '#comportamiento' ).val()34 };35 //36 jQuery.post( ajaxurl, datos, function( resul ) {37 if( resul.ok )38 cdp_cookies_mensaje( resul.txt );39 else40 cdp_cookies_mensaje_error( resul.txt );41 }, 'json' );42}43//44function crear_paginas()45{46 //47 var datos = {48 action: 'crear_paginas',49 nonce_crear_paginas : cdp_cookies_info.nonce_crear_paginas50 };51 //52 jQuery.post( ajaxurl, datos, function( resul ) {53 if( resul.ok )54 {55 cdp_cookies_mensaje( resul.txt );56 jQuery( '#enlace_mas_informacion' ).val( resul.url_info );57 jQuery( '#enlace_politica' ).val( resul.url_politica );58 }59 else60 {61 cdp_cookies_mensaje_error( resul.txt );62 }63 }, 'json' );64}65//66jQuery( document ).ready( function( $ ) {67 // Ocultar/mostrar instrucciones68 $( '.cdp-cookies-bot-instrucciones' ).click( function() {69 $( '.cdp-cookies-instrucciones' ).toggle();70 } );71 // Radios más fáciles de pinchar72 $( 'form .cdp-cookies-radio' ).click( function() {73 $( this ).find( 'input' ).attr( 'checked', true );74 } );75 // Guardar config76 $( 'a.cdp-cookies-guardar' ).click( function() {77 guardar();78 } );79 // Crear pág. polÃtica80 $( 'a.cdp-cookies-crear-politica' ).click( function() {81 crear_paginas();82 } );83 // Ver pág. más info84 $( 'a.cdp-cookies-ver-mas-info' ).click( function() {85 window.open( $( '#enlace_mas_informacion' ).val() );86 } );87 // Ver pág. politica88 $( 'a.cdp-cookies-ver-politica' ).click( function() {89 window.open( $( '#enlace_politica' ).val() );90 } );91 // Vista previa del aviso92 $( 'a.cdp-cookies-vista-previa' ).click( function() {93 window.open( 94 cdp_cookies_info.siteurl + 95 '?cdp_cookies_vista_previa=1' +96 '&layout=' + $( '#layout' ).val() +97 '&comportamiento=' + $( '#comportamiento' ).val() +98 '&posicion=' + $( '#posicion' ).val() +99 '&alineacion=' + $( '#alineacion' ).val() +100 '&tema=' + $( '#tema:checked' ).val() +101 '&tam_fuente=' + $( '#tam_fuente' ).val()102 );103 } );...
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .type('input[name="q"]', 'navalia')4 .click('input[name="btnK"]')5 .wait('h3')6 .evaluate(() => document.querySelector('h3').innerText)7 .end()8 .then(console.log)9 .catch(console.error);
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .type('input[name="q"]', 'navalia')4 .click('input[name="btnK"]')5 .wait('h3')6 .evaluate(() => document.querySelector('h3').innerText)7 .end()8 .then(console.log)9 .catch(console.error);
Using AI Code Generation
1const { Chrome } = require('navalia');2async function main() {3 const chrome = new Chrome();4 await chrome.type('#lst-ib', 'navalia');5 await chrome.click('#tsbb');6 await chrome.wait('#resultStats');7 await chrome.screenshot('google.png');8 await chrome.close();9}10main();11const { Chrome } = require('navalia');12async function main() {13 const chrome = new Chrome();14 await chrome.type('#lst-ib', 'navalia');15 await chrome.click('#tsbb');16 await chrome.wait('#resultStats');17 await chrome.screenshot('google.png');18 await chrome.close();19}20main();21const { Chrome } = require('navalia');22async function main() {23 const chrome = new Chrome();24 await chrome.type('#lst-ib', 'navalia');25 await chrome.click('#tsbb');26 await chrome.wait('#resultStats');27 await chrome.screenshot('google.png');28 await chrome.close();29}30main();31const { Chrome } = require('navalia');32async function main() {33 const chrome = new Chrome();34 await chrome.type('#lst-ib', 'navalia');35 await chrome.click('#tsbb');36 await chrome.wait('#resultStats');37 await chrome.screenshot('google.png');38 await chrome.close();39}40main();41const { Chrome } = require('navalia');42async function main() {43 const chrome = new Chrome();44 await chrome.type('#lst-ib', 'navalia');45 await chrome.click('#tsbb');46 await chrome.wait('#resultStats');47 await chrome.screenshot('google.png');48 await chrome.close();49}50main();51const { Chrome } = require('navalia');52async function main() {
Using AI Code Generation
1const navalia = require('navalia');2const chrome = require('chrome-remote-interface');3const fs = require('fs');4const path = require('path');5const os = require('os');6const puppeteer = require('puppeteer');7const url = require('url');8const util = require('util');9const writeFileAsync = util.promisify(fs.writeFile);10const readFileAsync = util.promisify(fs.readFile);11const test = async () => {12 const browser = await navalia({ browser: 'chrome' });13 const page = await browser.newPage();14 await page.type('input[title="Search"]', 'puppeteer');15 await page.click('input[value="Google Search"]');16 await browser.close();17};18test();19### navalia([options])
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .navigate(url)4 .waitForSelector('input[type="text"]')5 .type('input[type="text"]', 'navalia')6 .waitForSelector('input[type="submit"]')7 .click('input[type="submit"]')8 .waitForSelector('h3.r a')9 .evaluate(() => document.querySelector('h3.r a').href)10 .then((href) => console.log(href))11 .catch((err) => console.error(err))12 .then(() => browser.close());13#### `new Navalia(options)`
Using AI Code Generation
1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 await page.screenshot({path: 'example.png'});5 await browser.close();6})();
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3 .navigate(url)4 .waitForSelector('input[type="text"]')5 .type('input[type="text"]', 'navalia')6 .waitForSelector('input[type="submit"]')7 .click('input[type="submit"]')8 .waitForSelector('h3.r a')9 .evaluate(() => document.querySelector('h3.r a').href)10 .then((href) => console.log(href))11 .catch((err) => console.error(err))12 .then(() => browser.close());13#### `new Navalia(options)`
Using AI Code Generation
1const navalia = require('navalia');2const browser = new navalia();3async function run() {4 await browser.launch();5 await browser.goto(url);6 const title = await browser.getTitle();7 console.log(title);8 await browser.close();9}10run();
Using AI Code Generation
1const navalia = require('navalia');2const chrome = require('chrome-remote-interface');3const fs = require('fs');4navalia.use(chrome)5navalia.launch({ headless: true })6 .then(browser => {7 return browser.newPage()8 .then(page => {9 .then(() => {10 return page.screenshot({ path: 'example.png' })11 .then(() => {12 console.log('Screenshot saved to example.png');13 return browser.close();14 });15 });16 });17 })18 .catch(error => {19 console.error(error);20 });21## `navalia.use(engine)`22- `name` - A string containing the name of the engine (e.g. 'chrome')23## `navalia.launch([options])`
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!