Best JavaScript code snippet using ng-mocks
index.ts
Source:index.ts
1import { Wallet } from "ethers"2import * as dotenv from "dotenv"3import { EntityMetadata, API, Models, ProcessMetadata, Network } from "dvote-js"4import { GatewayPool } from "dvote-js/dist/net/gateway-pool"5import { digestHexClaim } from "dvote-js/dist/api/census"6import { waitUntilVochainBlock } from "dvote-js/dist/util/waiters"7dotenv.config() // Load .env8const MNEMONIC = "whale pyramid cross pilot myself fashion life pottery motor symptom claim color"9const GATEWAY_BOOTNODE_URI = "https://bootnodes.vocdoni.net/gateways.dev.json"10const NETWORK_ID = "sokol"11const entityWallet: Wallet = Wallet.fromMnemonic(MNEMONIC, "m/44'/60'/0'/0/0")12const voterWallets: Wallet[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(idx => Wallet.fromMnemonic(MNEMONIC, "m/44'/60'/0'/0/" + idx))13let pool: GatewayPool14let votersPublicKeys: string[] = []15let merkleTreeOrigin: string16let merkleRoot: string17let processId: string = "0x35bde37ea31f18b5dbba6afff4fd2de24519c712cb0a4488ab17d16dbcef1c30"18// Code19async function connect() {20 // Get a pool of gateways to connect to the network21 pool = await GatewayPool.discover({ networkId: NETWORK_ID, bootnodesContentUri: GATEWAY_BOOTNODE_URI })22 await pool.connect()23}24const disconnect = () => pool.disconnect()25async function registerEntity() {26 // Make a copy of the metadata template and customize it27 const entityMetadata: EntityMetadata = Object.assign({}, Models.Entity.EntityMetadataTemplate)28 entityMetadata.name.default = "Vilafourier"29 entityMetadata.description.default = "Official communication and participation channel of the city council"30 entityMetadata.media = {31 avatar: 'https://ipfs.io/ipfs/QmWm23t4FdCYdEpTmYYWdjPZFepCvk9GJTSSMdv8xU3Hm9',32 header: 'https://ipfs.io/ipfs/Qmb4tMak41v6WigrFqovo6AATy23pNZGFCa9PHJDjg6kWz'33 }34 entityMetadata.actions = []35 console.log("Setting the entity metadata")36 const contentUri = await API.Entity.updateEntity(entityWallet.address, entityMetadata, entityWallet, pool)37 // Show stored values38 console.log("Entity defined")39 console.log(contentUri)40}41function populateCensusPublicKeys() {42 // Use reproduceable wallets of 10 users to populate our census with public keys43 voterWallets.forEach(wallet => {44 votersPublicKeys.push(wallet["signingKey"].publicKey)45 })46 console.log("Voter's public keys", votersPublicKeys)47}48async function publishVoteCensus() {49 // Prepare the census parameters50 const censusName = "Vilafourier all members " + Math.random().toString().substr(2, 6)51 const adminPublicKeys = [await entityWallet["signingKey"].publicKey]52 const publicKeyClaims = votersPublicKeys.map(k => digestHexClaim(k)) // hash the keys53 // As the census does not exist yet, create it54 let { censusId } = await API.Census.addCensus(censusName, adminPublicKeys, pool, entityWallet)55 console.log(`Added census "${censusName}" with ID ${censusId}`)56 // Add claims to the new census57 let result = await API.Census.addClaimBulk(censusId, publicKeyClaims, true, pool, entityWallet)58 console.log("Added", votersPublicKeys.length, "claims to", censusId)59 if (result.invalidClaims.length > 0) console.error("Invalid claims", result.invalidClaims)60 merkleRoot = await API.Census.getRoot(censusId, pool)61 console.log("Census Merkle Root", merkleRoot)62 // Make it available publicly63 merkleTreeOrigin = await API.Census.publishCensus(censusId, pool, entityWallet)64 console.log("Census published on", merkleTreeOrigin)65}66async function createVotingProcess() {67 const myEntityAddress = await entityWallet.getAddress()68 const myEntityId = API.Entity.getEntityId(myEntityAddress)69 const startBlock = await API.Vote.estimateBlockAtDateTime(new Date(Date.now() + 1000 * 60 * 5), pool)70 const numberOfBlocks = 6 * 60 * 24 // 1 day (10s block time)71 const processMetadata: ProcessMetadata = {72 "version": "1.0",73 "type": "poll-vote",74 "startBlock": startBlock,75 "numberOfBlocks": numberOfBlocks,76 "census": {77 "merkleRoot": merkleRoot,78 "merkleTree": merkleTreeOrigin79 },80 "details": {81 "entityId": myEntityId,82 "title": { "default": "Vilafourier public poll" },83 "description": {84 "default": "This is our test poll using a decentralized blockchain to register votes"85 },86 "headerImage": "https://images.unsplash.com/photo-1600190184658-4c4b088ec92c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80",87 "streamUrl": "",88 "questions": [89 {90 "type": "single-choice",91 "question": { "default": "CEO" },92 "description": { "default": "Chief Executive Officer" },93 "voteOptions": [94 { "title": { "default": "Yellow candidate" }, "value": 0 },95 { "title": { "default": "Pink candidate" }, "value": 1 },96 { "title": { "default": "Abstention" }, "value": 2 },97 { "title": { "default": "White vote" }, "value": 3 }98 ]99 },100 {101 "type": "single-choice",102 "question": { "default": "CFO" },103 "description": { "default": "Chief Financial Officer" },104 "voteOptions": [105 { "title": { "default": "Yellow candidate" }, "value": 0 },106 { "title": { "default": "Pink candidate" }, "value": 1 },107 { "title": { "default": "Abstention" }, "value": 2 },108 { "title": { "default": "White vote" }, "value": 3 }109 ]110 },111 ]112 }113 }114 processId = await API.Vote.createVotingProcess(processMetadata, entityWallet, pool)115 console.log("Process created:", processId)116 // Reading the process metadata back117 const metadata = await API.Vote.getVoteMetadata(processId, pool)118 console.log("The metadata is", metadata)119}120async function submitSingleVote() {121 // Get the user private key from the appropriate place122 const wallet = voterWallets[0]123 // Fetch the metadata124 const processMeta = await API.Vote.getVoteMetadata(processId, pool)125 console.log("- Starting:", await API.Vote.estimateDateAtBlock(processMeta.startBlock, pool))126 console.log("- Ending:", await API.Vote.estimateDateAtBlock(processMeta.startBlock + processMeta.numberOfBlocks, pool))127 console.log("- Census size:", await API.Census.getCensusSize(processMeta.census.merkleRoot, pool))128 console.log("- Current block:", await API.Vote.getBlockHeight(pool))129 console.log("- Current votes:", await API.Vote.getEnvelopeHeight(processId, pool))130 await waitUntilVochainBlock(processMeta.startBlock, pool, { verbose: true })131 console.log("Submitting vote envelopes")132 // Hash the voter's public key133 const publicKeyHash = digestHexClaim(wallet["signingKey"].publicKey)134 // Generate the census proof135 const merkleProof = await API.Census.generateProof(processMeta.census.merkleRoot, publicKeyHash, true, pool)136 // Sign the vote envelope with our choices137 const choices = [1, 2]138 const voteEnvelope = await API.Vote.packagePollEnvelope({ votes: choices, merkleProof, processId, walletOrSigner: wallet })139 // If the process had encrypted votes:140 // const voteEnvelope = await packagePollEnvelope({ votes, merkleProof, processId, walletOrSigner: wallet, encryptionPubKeys: ["..."] })141 await API.Vote.submitEnvelope(voteEnvelope, pool)142 console.log("Envelope submitted")143 // wait 10 seconds144 await new Promise(resolve => setTimeout(resolve, 1000 * 10))145 // Compute our deterministic nullifier to check the status of our vote146 const nullifier = await API.Vote.getPollNullifier(wallet.address, processId)147 const status = await API.Vote.getEnvelopeStatus(processId, nullifier, pool)148 console.log("- Registered: ", status.registered)149 console.log("- Block: ", status.block)150 console.log("- Date: ", status.date)151}152async function submitVotes() {153 const processMeta = await API.Vote.getVoteMetadata(processId, pool)154 console.log("- Starting:", await API.Vote.estimateDateAtBlock(processMeta.startBlock, pool))155 console.log("- Ending:", await API.Vote.estimateDateAtBlock(processMeta.startBlock + processMeta.numberOfBlocks, pool))156 console.log("- Census size:", await API.Census.getCensusSize(processMeta.census.merkleRoot, pool))157 console.log("- Current block:", await API.Vote.getBlockHeight(pool))158 console.log("- Current votes:", await API.Vote.getEnvelopeHeight(processId, pool))159 await waitUntilVochainBlock(processMeta.startBlock, pool, { verbose: true })160 console.log("Submitting vote envelopes")161 // For each wallet from 2..10, submit a vote162 await Promise.all(voterWallets.slice(1).map(async wallet => {163 // Hash the voter's public key164 const publicKeyHash = digestHexClaim(wallet["signingKey"].publicKey)165 // Generate the census proof166 const merkleProof = await API.Census.generateProof(processMeta.census.merkleRoot, publicKeyHash, true, pool)167 // Sign the vote envelope with our choices168 const choices = [1, 2]169 const voteEnvelope = await API.Vote.packagePollEnvelope({ votes: choices, merkleProof, processId, walletOrSigner: wallet })170 // If the process had encrypted votes:171 // const voteEnvelope = await packagePollEnvelope({ votes, merkleProof, processId, walletOrSigner: wallet, encryptionPubKeys: ["..."] })172 await API.Vote.submitEnvelope(voteEnvelope, pool)173 process.stdout.write(".")174 }))175}176async function fetchResults() {177 const { questions } = await API.Vote.getResultsDigest(processId, pool)178 console.log("Process results", questions)179}180async function forceEndingProcess() {181 // Already canceled?182 const canceled = await API.Vote.isCanceled(processId, pool)183 if (canceled) return console.log("Process already canceled")184 // Already ended?185 const processMeta = await API.Vote.getVoteMetadata(processId, pool)186 const currentBlock = await API.Vote.getBlockHeight(pool)187 if (currentBlock >= (processMeta.startBlock + processMeta.numberOfBlocks)) return console.log("Process already ended")188 console.log("Canceling process", processId)189 await API.Vote.cancelProcess(processId, entityWallet, pool)190 console.log("Done")191}192// Launch all the steps193connect()194 .then(() => registerEntity())195 .then(() => populateCensusPublicKeys())196 .then(() => publishVoteCensus())197 .then(() => createVotingProcess())198 .then(() => submitSingleVote())199 .then(() => submitVotes())200 .then(() => fetchResults())201 .then(() => forceEndingProcess())202 .catch(err => console.error(err))...
render.component.ts
Source:render.component.ts
1import { Component, OnInit, OnDestroy } from '@angular/core';2import { Router, ActivatedRoute, ParamMap, Params } from '@angular/router';3import { Subject } from 'rxjs';4import { AuthService } from '@shared/auth';5import { switchMap, catchError, tap, takeUntil } from 'rxjs/operators';6import { FormBuilderService, FormsService } from '../services';7interface WindowWithToken extends Window {8 WORKFLOW_TOKEN: string;9}10@Component({11 selector: 'app-forms-view',12 templateUrl: './render.component.html'13})14export class ViewFormComponent implements OnInit, OnDestroy {15 _workflow_src_doc: string;16 existing: boolean;17 processMeta: { processId: string, taskId: number } | null = null;18 private destroy$ = new Subject<void>();19 constructor(20 private _builder: FormBuilderService,21 private _route: ActivatedRoute,22 private router: Router,23 private _formSvc: FormsService24 ) { }25 get referRoute(): any[] {26 if (this.processMeta && this.processMeta.processId) {27 return ['process', this.processMeta.processId];28 }29 return ['forms'];30 }31 ngOnInit() {32 this.getProcessMeta();33 this.getForm().pipe(34 tap(srcDoc => this._workflow_src_doc = srcDoc),35 catchError(err => this.router.navigate(this.referRoute))36 ).subscribe();37 (window as WindowWithToken).WORKFLOW_TOKEN = AuthService.getToken();38 }39 handleSuccessfulSubmission() {40 // success toastr here41 this._formSvc.notifyEngine(this.processMeta.taskId).subscribe();42 this.router.navigate(this.referRoute);43 }44 getForm() {45 return this._route.paramMap.pipe(46 switchMap((params: ParamMap) => {47 if (isNaN(+params.get('formId'))) {48 throw new Error('Invalid form Id');49 } else {50 return this._builder.renderForm(+params.get('formId'));51 }52 })53 );54 }55 getProcessMeta(): void {56 this._route.queryParams.pipe(takeUntil(this.destroy$))57 .subscribe((queryParams: Params) => {58 // @ts-ignore59 this.processMeta = {};60 const rawTaskId = queryParams['task'];61 if (rawTaskId && !isNaN(parseInt(rawTaskId, 10))) {62 this.processMeta.taskId = parseInt(rawTaskId, 10);63 }64 this.processMeta.processId = queryParams['process'];65 });66 }67 ngOnDestroy() {68 this.destroy$.next();69 }...
processMeta.spec.js
Source:processMeta.spec.js
...18 { [CONDITIONS]: [["orientation", ":", "portrait"]] },19 { [CONDITIONS]: [["width", ">", 100]] }20 ]21 };22 const processedMeta = processMeta(meta);23 expect(meta).not.toBe(processedMeta);24 expect(getConditionFunction).toHaveBeenCalledTimes(3);25 expect(getConditionFunction.mock.calls[0][0]).toEqual([26 ["orientation", ":", "landscape"]27 ]);28 expect(getConditionFunction.mock.calls[1][0]).toEqual([29 ["orientation", ":", "portrait"]30 ]);31 expect(getConditionFunction.mock.calls[2][0]).toEqual([["width", ">", 100]]);32 expect(typeof processedMeta[QUERIES][0].conditionFunction).toBe("function");33 expect(processedMeta[QUERIES][0].conditionFunction()).toBe(1);34 expect(typeof processedMeta[QUERIES][1].conditionFunction).toBe("function");35 expect(processedMeta[QUERIES][1].conditionFunction()).toBe(2);36 expect(typeof processedMeta[QUERIES][2].conditionFunction).toBe("function");37 expect(processedMeta[QUERIES][2].conditionFunction()).toBe(3);38});39test("should return null for invalid configurations", () => {40 const errorRegex = /^Invalid meta object/;41 expect(() => processMeta()).toThrow(errorRegex);42 expect(() => processMeta({})).toThrow(errorRegex);43 expect(() => processMeta([])).toThrow(errorRegex);44 expect(() => processMeta("")).toThrow(errorRegex);45 expect(() => processMeta(false)).toThrow(errorRegex);46 expect(() => processMeta(42)).toThrow(errorRegex);...
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!!